Passing json data ajax to Spring boot - java

I'm trying to passing Json Data with Ajax to SpringBoot, but it's throwing error, What is the mistake in my program Pls tell me and suggest me. what is the mistake.
var emailId = {"emailId" : userEmail};
$.ajax({
url : "/api/v1/leadsquard/user/emailId",
type : "GET",
data : JSON.stringify(emailId),
dataType : "text",
contentType: "application/json",
success: function (response) {
alert("Success "+ JSON.stringify(response));
},
error: function(response) {
alert("Success "+ JSON.stringify(response));
}
});
Controller Class
#RestController
#RequestMapping(value = "/api/v1")
public class LeadSquardController {
#Autowired
LeadSquardService leadSquardService;
#GetMapping("leadsquard/user/emailId")
#ResponseBody
public String getByEmailaddress(#RequestBody Object emailId) {
System.out.println("Email : " + emailId.getClass().getName()); //Testing line
System.out.println("Email : " + emailId); //Testing line
return "";
}
}

Why are you using RequestBody when you are sending it as GET request. I would have used POST instead.
Use #PostMapping for your resource and make a POST ajax call.

Related

Ajax request showing error occured:Spring mvc maven project

When ajax call happens it shows error occurred without any tomcat error logs. While on browser is displays 400.
Here is my ajax call.
var data = {
"topic" : $("#topic").val()}
$.ajax({
type : "GET",
contentType : "application/json",
url : "./saveSyllabus",
data : JSON.stringify(data),
dataType : 'json',
timeout : 100000,
success : function(data) {
console.log("SUCCESS: ", data);
alert("Record Added Successfully!!")
},
error : function(e) {
console.log("ERROR: ", e);
alert("Error Occured!!")
},
done : function(e) {
console.log("DONE");
enableSearchButton(true);
}
});
Controller code:
#Controller
public class RegistrationController {
#Autowired
UserCreationService userCreationService;
#Autowired
SyllabusService syllabusService;
#RequestMapping(value="/saveSyllabus",method=RequestMethod.GET)
public #ResponseBody String saveSyllabus(#RequestParam String topic) {
System.out.println("in registration controller");
Integer id= syllabusService.saveSyllabus(syllabusDetails);
return id;
}
}
I have added required dependancies also:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
Your problem is the controller is configured to response in body, but your are doing a redirect, in your case it seems you want the redirect so remove the #ResponseBody:
#RequestMapping(value="/saveSyllabus",method=RequestMethod.GET)
public String saveSyllabus(#RequestParam String topic,RedirectAttributes rd) {
System.out.println("in registration controller");
Integer id= syllabusService.saveSyllabus(syllabusDetails);
if(id>0){
rd.addFlashAttribute("id", 1);
} else {
rd.addFlashAttribute("id",0);
}
return "redirect:"+ "/register";
}
As your are doing a redirect this sould be a browser URL call and not an Ajax call
Instead if you want to reponse to the body try this
var data = {
"topic" : $("#topic").val()}
$.ajax({
type : "GET",
contentType : "application/json",
url : "./saveSyllabus",
data : JSON.stringify(data),
dataType : 'json',
timeout : 100000,
success : function(data) {
console.log("SUCCESS: ", data);
alert("Record Added Successfully!!")
},
error : function(e) {
console.log("ERROR: ", e);
alert("Error Occured!!")
},
done : function(e) {
console.log("DONE");
enableSearchButton(true);
}
});
and
#RequestMapping(value="/saveSyllabus",method=RequestMethod.GET)
public #ResponseBody String saveSyllabus(#RequestBody String topic) {
System.out.println("in registration controller");
Integer id= syllabusService.saveSyllabus(syllabusDetails);
return String.valueOf(id);
}
note #ReuqestParam change to #RequestBody and the method content changed too
You're returning a String value from #Controller using #ResponseBody but your AJAX is expecting a JSON response from Controller datatype: 'json',. Change your AJAX Response expectation to HTML datatype : 'HTML', and it will return status 200!

POSTing data return error instead of success

I am new to Spring MVC and I am trying to send my data to Spring-MVC Controller using AJAX, on button click. I have written this code (given below) but I am getting error instead of success. please tell what can be the issue?
AJAX:
function add() {
var name = $('#name').val();
$.ajax({
url : "/addUser",
data : name,
type : "POST",
async: false,
success : function(response) {
alert( response );
},
error : function() {
alert("error....");
}
});
}
JAVA
#RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String addUser(#ModelAttribute("UserTest") String name) {
//task
return name;
}

Why does Spring MVC respond with 415 for an Ajax query requesting JSON?

I've read 3/4 posts on Stack plus many other examples to try figure this out but I've no clue ! Need some pointers please !!
Creating my first Ajax update through Spring-MVC and I keep getting a Status 415 being returned by my submission with The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request accept
JQuery... Version 3.1.1
function updateScore () {
$("div#results").append("<p>Posting User/Game ID " + this.id + " Value " + this.value + "</p>");
var prediction = {}
prediction["id"] = this.id;
prediction["value"] = this.value;
$.ajax({
type : "POST",
contentType : "application/json",
url : "/tournament/setPrediction.html",
data : JSON.stringify(prediction),
dataType : 'json',
timeout : 100000,
success : function(data) {
console.log("SUCCESS: ", data);
displayResult(data, "success");
},
error : function(e) {
console.log("ERROR: ", e);
displayResult(e, "error");
},
done : function(e) {
console.log("DONE");
displayResult(true, "done");
}
});
}
Controller... Spring version 4.3.5
#RestController
public class PredictionAjaxController {
#ResponseBody
#RequestMapping(value = "/setPrediction.html", consumes = MediaType.APPLICATION_JSON_VALUE,
method = RequestMethod.POST, headers="Accept=application/json")
public Prediction setUserPrediction(#RequestBody PredictionPojo prediction) {
Prediction result = new Prediction();
System.out.println("AJAX call made in controller");
return result;
}
}
Finally a very simple POJO for the JSon to map to
public class PredictionPojo {
private String id;
private String value;
Getters & Setters... ()
}
I've added different things onto the controller now to try and resolve, didn't start with it all ! I'm completely confuddled !
Should be so simple...
DH
You have an error in your ajax call, you are sending a string instead of a JSON object. Also I don't think is necessary to specify the consumes and headers attributes in you #RequestMapping annotation in your setUserPrediction method, The PredictionAjaxController is already defined as a RestController. Your ajax should be:
$.ajax({
// .......
data : prediction,
// .......
});

JQuery, AJAX, POST request, parameters lost

My web application is basen on Spring MVC (4.0.5).
I'm trying to send a POST request through AJAX, using jQuery (v. 2.1.1):
function deleteItem(id) {
alert("Deleting " + id);
$.ajax({
url: "ajax/delete_item",
type: 'POST',
dataType: 'html',
data: {"id": id},
contentType: 'application/json',
mimeType: 'application/json',
success: function(data) {
var txt = data;
$('#message').html(txt);
},
error: function(data, status, err) {
$('#message').html(err);
}
});
}
The Controller's method is called successfully but there are no parameters in the request:
#RequestMapping(value = "/ajax/delete_item", method = RequestMethod.POST)
public #ResponseBody String ajaxDelete(HttpServletRequest request) {
Enumeration<String> en = request.getParameterNames();
while (en.hasMoreElements()) {
String pname = en.nextElement();
System.out.println("//// " + pname); // just for test
}
String idStr = request.getParameter("id");
Integer id = Integer.parseInt(idStr);
//...
Why the request parameter is lost? Not just the value, the parameter itself is also lost.
What's wrong here?
If you are passing content type contentType: 'application/json' from ajax then add that settings in Spring method declaration as below: ( add produces = "application/json" in definition)
#RequestMapping(value = "/ajax/delete_item", method = RequestMethod.POST , produces = "application/json")
public #ResponseBody String ajaxDelete(HttpServletRequest request) {
also there's one more caveat that,
You are mentioning both datatype and mimeType but it is not uniform.
mimeType: 'application/json' should be written with dataType: 'json' and not html.
I am not 100% sure what is wrong with your solution but I can give you an example that works for me
The AJAX request using Jquery :
// Do AJAX
$(function () {
$.post(mobileUrl + "/leave/requestLeave",
{ startDate: startDate, endDate: endDate, leaveTypeId: leaveTypeId,
notes: notes, isStartDayHalfDay: isStartDayHalfDay, isHalfDayEndDay: isHalfDayEndDay },
function (response) {
$('#feedbackTextArea').show();
}
);
});
And the controller method
#RequestMapping(value = "/requestLeave", method = RequestMethod.POST)
#ResponseBody
public String createOrUpdateNewForm(String startDate, String endDate, String leaveTypeText, String leaveTypeId,
String notes, String isStartDayHalfDay, String isHalfDayEndDay) {
startDate = new DateTime(startDate).toDate() etc
}
}
One thing to remember is that the parameter names in the ajax request should match the names of the variables in the controller method implementation
$("#drpop").change(function () {
var code = $(this).val();
$.ajax({
url: '/Ordering/OrderingTable',
type: 'post',
datatype: 'json',
data: { OperCode: code },
success:function(msg){
alert(msg);
} }); });
[HttpPost]
public ActionResult OrderingTable(string OperCode)
{
Orderingbll order = new Orderingbll();
var result = order.ListCategory(OperCode);//here you write your code
return Json(result,JsonRequestBehavior.AllowGet);
}

AJAX Post - Performed in JSP, need to return java based variables in the AJAX POST Success function

I am using ajax post within a JSP, to send json data to a servlet java class. Within the servlet controller class I used getparameter to get the data being sent from the calling JSP.
This all works fine, to this point. I then initate processing of the data in from this servlet class, and I need to formulate a data response to send back to the calling JSP.
Is there a way that I can hold the data in variables within the servelt class, and as part of the success function (within my AJAX post) access this data?
My AJAX Post code:
$.ajax({
type: "POST",
url: url,
dataType: "text", // [text, xml, json, script, text, html]
data: {postData : myData, sendURL : postUrl},
success: function(data, textStatus, jqXHR) {
alert('Success post to URL entered \n\n The data returned the following: ' + data);
},
error:function (xhr, ajaxOptions, thrownError){
alert('Error xhr : ' + xhr.status);
alert('Error thrown error: ' + thrownError);
}
//complete: alert('complete')
});
My Servlet Controller code:
#RequestMapping("/postData")
public String postData(Model model, HttpServletRequest request) throws Throwable{
String postData = request.getParameter("postData");
String sendURL= request.getParameter("sendURL");
System.out.println(this.getClass() + " : postData : " + postData);
System.out.println(this.getClass() + " : gatewayURL : " + gatewayURL);
/* Process data and formulate a response.... */
String responseText = processedResponseText; // This processedResponseText was populated in the internal processing
String responseCode = processedResponseCode; // This processedResponseCode was populated in the internal processing
return "callingJSP";
}
As part of my AJAX Post - Success function, how can I get these two variables (responseText and responseCode) back to the calling JSP?
Many thanks
If you know the structure of the data that's coming in (you should!), create an object that the post data can be serialized to (I'm assuming myData is json?... if not, it should be!) by the servlet. The spring framework provides the #RequestBody annotation to deserialize the incoming json to your object. When the servlet needs to respond, do what #Jigar recommended: wrap your response in an object. The spring framework provides the #ResponseBody annotation to serialize your response to json. It could look something like this:
Your js:
var myData = { postId: 1, comment: "this is great!" };
$.ajax({
type: "POST",
url: url,
dataType: "text", // [text, xml, json, script, text, html]
data: {postData : myData, sendURL : postUrl},
success: function(data, textStatus, jqXHR) {
var jsonRepsonse = JSON.parse(data);
alert('Success post to URL entered \n\n The data returned the following: ' + jsonRepsonse.responseText + ", " + jsonRepsonse.responseCode);
},
error:function (xhr, ajaxOptions, thrownError){
alert('Error xhr : ' + xhr.status);
alert('Error thrown error: ' + thrownError);
}
//complete: alert('complete')
});
Your Java object:
class Comment {
private long postId;
private String comment;
// getters & setters
}
Your wrapped response object:
class AjaxResponse{
private String responseText;
private String responseCode;
//other stuff
}
The handler function in your controller:
#RequestMapping("/postData")
public #ResponseBody postData(Model model,
#RequestBody Comment comment,
HttpServletRequest request) throws Throwable{
String sendURL= request.getParameter("sendURL");
System.out.println(this.getClass() + " : comment : " + comment.toString());
/* Process data and formulate a response.... */
AjaxResponse ajaxResponse = new AjaxResponse(processedResponseText, processedResponseCode);
return ajaxResponse;
}
Ideally your AjaxResponse contains another object instead of text that provides more information about the response. For example, you may want to change your AjaxResponse object as follows:
class CommentResponse extends Comment {
private long commentId;
private Timestamp entryDateTime;
// etc
}
class AjaxResponse{
private CommentResponse commentResponse;
private String responseCode;
//other stuff
}
Doing this helps you immensely when receiving the response on the front end, but it depends on what you need.
Also..
Success will return the response
success: function(data, textStatus, jqXHR) {
alert('Success post to URL entered \n\n The data returned the following: ' + data);
},
No need of XHR and textStatus in the success function should be like :
success: function(response) {
alert('Success post to URL entered \n\n The data returned the following: ' + response.responseText);
},

Categories