How to pass Parameter from Ajax to RestController in Spring Boot - javascript

i try to pass Parameter from Ajax to RestController to send a Email.
That is the Controller Post Methode to send the Enail
#RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody String create(#RequestParam("covere") String covere, #RequestParam("title") String title,
#RequestParam("username") String username, #RequestParam("usernameto") String usernameto) {
try {
mailService.sendMail(covere, title, username, usernameto);
return "sendmail";
} catch (MailException e) {
e.printStackTrace();
}
return "sendmail";
}
That is the Ajax to Call the Post and pass the Variable to send Message
$("#vuta").on("click", function(e) {
var EmailData = {
"covere" : "John",
"title" :"Boston",
"username" :"test#yahoo.fr",
"usernameto" :"test#yahoo.fr"
}
$.ajax({
type: "POST",
url: "/emailsend",
dataType : 'json',
contentType: 'application/json',
data: JSON.stringify(EmailData)
});
});
I have this Error when i send the Email
Required String parameter 'covere' is not
present","path":"/emailsend"}
Thank for help

Your controller is expecting parameters via Query String. You can use $.param to format the object as query string and send it in the URL:
$("#vuta").on("click", function(e) {
var EmailData = {
"covere" : "John",
"title" :"Boston",
"username" :"test#yahoo.fr",
"usernameto" :"test#yahoo.fr"
}
$.ajax({
type: "POST",
url: "/emailsend?" + $.param(EmailData),
dataType : 'json',
contentType: 'application/json'
});
});

Related

Validate Anti forgery key not working with ajax post

I have tried to use validate antiforgery token with ajax post request but the response is that no root element found .
i remove the antiforgery token it works perfectly .
Here is my code :
javascript ;
function Save() {
let GroupName = GetElementValue("GroupName");
let GroupId = GetElementValue("GroupId");
var Group = {
__RequestVerificationToken: gettoken(),
GroupId: :1",
GroupName: "My Group Name"
};
if (IsFormValid("GroupForm")) {
AjaxPost("/Groups/AddGroup", Group).done(function () {
GetGroups();
});
}
}
function gettoken() {
var token = '#Html.AntiForgeryToken()';
token = $(token).val();
return token;
}
function AjaxPost(url, data) {
return $.ajax({
type: "post",
contentType: "application/json;charset=utf-8",
dataType: "json",
responseType: "json",
url: url,
data: JSON.stringify(data)
});
}
I have also tried this :
$.ajax({
type: "POST",
url: "/Groups/AddGroup",
data: {
__RequestVerificationToken: gettoken(),
GroupId: 1,
GroupName: "please work"
},
dataType: 'json',
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
});
Here Is The backend :
[HttpPost]
[ValidateAntiForgeryToken]
public void AddGroup([FromBody] GroupView Group)
{
if (Group.GroupName.Trim().Length>0)
{
bool existed = _context.Groups.Any(x => x.GroupName.ToLower().TrimEnd().Equals(Group.GroupName.ToLower().TrimEnd()));
if (!existed)
{
Groups group = new Groups()
{
GroupName = Group.GroupName
};
_context.Groups.AddAsync(group);
_context.SaveChanges();
int? groupId = group.GroupId;
}
}
}
And Here Is My Class GroupView
public class GroupView
{
public string GroupId { get; set; }
public string GroupName { get; set; }
}
I want to use the method where i send the serial token with my data normally ,
how can i make it works ?
any help!
In ASP.NET Core you can pass antiforgery token either via form or headers. So I can suggest 2 solutions for you.
Solution 1. Headers
In order to let the framework read token from headers you need to configure AntiforgeryOptions and set HeaderName to non null value. Add this code to Startup.cs
//or if you omit this configuration
//HeaderName will be "RequestVerificationToken" by default
services.AddAntiforgery(options =>
{
options.HeaderName = "X-CSRF-TOKEN"; //may be any other valid header name
});
And pass antiforgery token in AJAX
function Save() {
//..
//no need to set token value in group object
var Group = {
GroupId: "1",
GroupName: "My Group Name"
};
//..
}
function AjaxPost(url, data) {
return $.ajax({
type: "post",
contentType: "application/json;charset=utf-8",
dataType: "json",
responseType: "json",
headers: {
"X-CSRF-TOKEN": gettoken()
},
url: url,
data: JSON.stringify(data)
});
Solution 2. Form
You have already tried to pass token via form but it didn't work. Why? The reason is that the default implementation of IAntiforgeryTokenStore (is used for reading tokens from request) cannot read antiforgery token from json but reads it as form data. If you want to make it work then don't stringify request data and remove contentType property from $.ajax call. JQuery will set appropriate content type and serialize data respectively for you.
//all other original code is unchanged, group needs to contain a token
function AjaxPost(url, data) {
return $.ajax({
type: "post",
dataType: "json",
responseType: "json",
url: url,
data: data
});
Also you need to remove [FromBody] attribute from action parameter to let model binder properly bind model in this case
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult AddGroup(GroupView group)
For FromBody, it will bind the model from application/json, but CSRF would not read the token from body.
For the simplest way, you could add the header with RequestVerificationToken.
Controller
[HttpPost("/Groups/AddGroup")]
[ValidateAntiForgeryToken]
public void AddGroup([FromBody] GroupView Group)
{
}
Client
<script type="text/javascript">
$(document).ready(function(){
var Group = {
__RequestVerificationToken: gettoken(),
GroupId: 1,
GroupName: "My Group Name"
};
AjaxPost("/Groups/AddGroup", Group).done(function () {
GetGroups();
});
});
function gettoken() {
var token = '#Html.AntiForgeryToken()';
token = $(token).val();
return token;
}
function AjaxPost(url, data) {
return $.ajax({
type: "post",
contentType: "application/json;charset=utf-8",
dataType: "json",
responseType: "json",
url: url,
headers: {
"RequestVerificationToken": gettoken()
},
data: JSON.stringify(data)
});
}
</script>

Cannot retrieve data from ajax with request

I'm having problems retrieving data from an ajax post in an easy aplication, just making some tests.
I'm working with something easy:
I have 2 classes:
Controller.java:
#RequestMapping(value = "/urlpost", method = {RequestMethod.GET, RequestMethod.POST} )
public urlPostTest(HttpServletRequest request, HttpServletResponse response) {
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("post_name");
String age = request.getParameter("post_age");
System.out.println("His name is: " + name);
System.out.println("His age is: " + age);
}
And
PostingClass.js
function posting(){
$.ajax({
url: 'urlpost',
method: 'POST',
data: {
'post_name': "Peter",
'post_age': "22"
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
console.log("Send data: SUCCES.");
}
});
}
The ajax goes correctly to the url, but the request is always null.
What could be the problem?.
Thanks.
request.getParameter("post_name"); // works on application/x-www-form-urlencoded
To get the data from a application/json request, use something like this:
String jsonStr = IOUtils.toString(request.getInputStream());
JSONObject jsonObj = new JSONObject(jsonStr);
String name = getString("name");

Error while calling Webapi in my asp.net project

This is my api code that return successfull json data while using get method
public Question[] Get() {
getQuestion obj = new AllDataAccess.getQuestion();
return obj.questionList().ToArray();
}
This is my post method data that accept the value and save in database
public void Post([FromBody] string question) {
SaveQuestion obj = new AllDataAccess.controller.SaveQuestion();
obj.savaData(question);
}
This is the method that call my api
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'http://localhost:53893/api/values',
data: "{'question':'" + $("#submit").value + "'}",
dataType: 'json',
async: false,
success: function(data, status) {
console.log(status);
},
error: function(err) {
console.log(err);
}
});
Now the problem is when i post the data with one textbox value its give me a message in console that "nocontent" and record save in data base with null value
It seems that your ajax url is wrong. You should specify the action name (post). Also, use JSON.stringify to retrieve proper json from javascript object.
var postData = { question:$("#submit").val() };
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'http://localhost:53893/api/values/post',
data: JSON.stringify(postData),
dataType: 'json',
success: function (data,status) {
console.log(status);
},
error: function (err) {
console.log(err);
}
});
In the server side, you should create a model class for Post method;
public class PostInput
{
public string Question { get; set; }
}
And then Post method looks like;
[HttpPost]
public void Post([FromBody]PostInput input)
{
SaveQuestion obj = new AllDataAccess.controller.SaveQuestion();
obj.savaData(question);
}
If you want to use FromBody, you can do so.
JavaScript
$.ajax({
type: "POST",
//default content-type, could be omitted
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
url: 'http://localhost:53893/api/values/post',
data: {'': $("#submit").val()}
});
API action
[HttpPost]
public void Post([FromBody]string question)
{
SaveQuestion obj = new AllDataAccess.controller.SaveQuestion();
obj.savaData(question);
}
You had these issues.
Wrong content-type for your ajax call.
Data was not posted correctly.
val() should be used instead of .value.
API action should be decorated with [HttpPost].

ajax email pass spring mvc

How to pass email id via ajax call (not as string), i need to catch that email parameter in spring controller.
$.ajax({
type : "POST",
contentType : "application/json",
data: data,
dataType: "text",
url : "<%=request.getContextPath()%>/methodName";,
success : function(data){
}
});
Java code:
#RequestMapping(value="/methodName/{email}", method =RequestMethod.POST,produces="application/json")
#ResponseBody
public String resetPassword(#PathVariable(value = "email") String email) throws Exception{
//do something
return "success";
}
The below code did the trick.
$.ajax({
type : "POST",
data: {
'email': email
},
url : "<%=request.getContextPath()%>/methodName";,
success : function(data){
}
});
#RequestMapping(value="/methodName", method =RequestMethod.POST)
#ResponseBody
public String resetPassword(#RequestParam(value = "email") String email) throws Exception{
//do something
return "success";
}

Error 405 : POST method not found while Sending JSON to Java Controller (Ajax)

I've a problem with sending JSON data to my Java Controller.
I have the following methode in my JSP file :
$.ajax({
type: "POST",
url: "/addPerson.html",
data: JSON.stringify({
aanvraag_id : chosenAanvraagId,
sharingbox_id : chosenSharingboxId
}),
contentType: 'application/json',
success: function(data) {
alert("de operatie is uitgevoerd");
}
});
This is my controller:
#RequestMapping(value = { "/addPerson" }, method = RequestMethod.POST , headers = {"Content-type=application/json"})
#ResponseBody
public JsonResponse addPerson(#RequestBody Person person) {
System.out.println(person.toString());
return new JsonResponse("OK", "");
}
When I call the ajax method I get a error
Status Code 405 : "POST method not found."
Anyone who knows what the problem is here?
Thanks in advance !
you have to change the url in your JSP
$.ajax({
type: "POST",
url: "/addPerson.html", // you can't write .html here, it should just be "/addPerson"
data: JSON.stringify({
aanvraag_id : chosenAanvraagId,
sharingbox_id : chosenSharingboxId
}),
contentType: 'application/json',
success: function(data) {
alert("de operatie is uitgevoerd");
}
});

Categories

Resources