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;
}
On the click of a button I am sending a JSON to the Java Server side via an API POST call.On validating the JSON, the server side function return a String.
How do I access that string on my JavaScript client side?
That String will tell me whether the JSON is valid or not.
You can use parseJSON(json) function in jQuery, for example:
function getValue(actionName) {
$j.ajax({
url: actionName + ".do",
data: {
"action" : "getJsonValue"
},
dataType: "json",
success: function(response) {
if (response.errorCode) {
showErrorMessage(response.errorMessage);
return;
}
response = $j.parseJSON(response);
return response;
},
});
}
I am performing an AJAX request this way
$.ajax({
type: 'GET',
url: 'http://hosti[:8080/OrderSnacks/oms/toppings?topping=' + id_attr_val,
jsonpCallback: 'jsonCallback',
cache: true,
dataType: 'jsonp',
jsonp: false,
success: function (response) {
console.log(response);
},
error: function (e) {
$("#divResult").html("WebSerivce unreachable");
}
});
});
Inside my REST service call , i am unable to receive this parameter
#Path("/toppings")
public class ToppingService {
#GET
#Consumes("application/text")
#Produces("application/json")
public String getData(#PathParam("toppingid") String toppingid) {
return "";
}
I have tried all the options that is
public String getData(#QueryParam("toppingid") String toppingid) {
}
public String getData(#PathParam("toppingid") String toppingid) {
}
But nothing is working .
Could you please tell me how to receive those parameters ??
You have a problem : you send topping but you ask for toppingid.
I am trying to collect all the form data and send it as a XML to Controller. This XML will further be sent to back end which will take care of it.
There is no need to marshal this XML into an Object.After receiving this XML I just need to send a String success message back.
It is half working. I am able to receive XML message from UI page and able to print it on console. But when I just send success message back UI ajax call receives No conversion from text to application/xml
#RequestMapping(value="/save",method=RequestMethod.POST,consumes={"application/json", "application/xml", "text/xml","text/plain"})
#ResponseBody public String handleSave(#RequestBody String formData)
{
System.out.println("comes here");
System.out.println(formData);
return "Success";
}
$('form').submit(function () {
$.ajax({
url: $(this).attr('action'),
type: 'POST',
processData: false,
data: collectFormData1(),
headers: {
"Content-Type":"application/xml"
},
dataType: 'application/xml',
success: function (data) {
alert('Success:'+data)
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('jqXHR:'+jqXHR+'\n'+'textStatus:'+'\n'+textStatus+'errorThrown::'+errorThrown);
}
});
return false;
});
Try to remove dataType: 'application/xml' from jquery code.
As mentioned in documentation: DataType: The type of data that you're expecting back from the server.
(http://api.jquery.com/jQuery.ajax/)
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);
},