jQuery code:
function ajaxsubmit(){
$.ajax({
url: "/update",
type: "POST",
dataType: "html"
}).success(function(data) {
$('#result').html(data);
});
}
and my Java function:
public static Result ajaxupdate() {
String done = "very good";
return ok("very good").as("text/plain");
}
the alert is giving [object Object]
, instead of plain text "very good"
. why?
ajax post method. The reason was my response was not in the JSON format so there was no need for the dataType: 'json' line in the submit method. In my case, the returned response was in text format that's why it was not going to success event. Solution: Remove dataType: 'json' line.
AJAX success is a global event. Global events are triggered on the document to call any handlers who may be listening. The ajaxSuccess event is only called if the request is successful. It is essentially a type function that's called when a request proceeds.
ajax() function returns the XMLHttpRequest object that it creates. Normally jQuery handles the creation of this object internally, but a custom function for manufacturing one can be specified using the xhr option.
Yes, it is deprecated in jQuery 1.8 onwards.
you want to use:
alert(JSON.stringify(data));
so you JavaScript will look like:
function ajaxsubmit(){
$.ajax({
url: "/update",
type: "POST",
}).complete(function(data) {
alert(JSON.stringify(data));
});
}
Your Java code looks like it is wrapping your string into an object before it sends it back to the client, JSON.stringify() will show you the structure of the object that is being returned and from there you can work out what property of the returned object contains your return variable (Probably something like data.data or data.return)
add dataType: "text" and change complete() with success()
function ajaxsubmit(){
$.ajax({
url: "/update",
type: "POST",
dataType: "html"
}).success(function(data) {
$('#result').html(data);
});
}
The jQuery documentation clearly answers your question. From http://api.jquery.com/jQuery.ajax/
complete(jqXHR, textStatus)
<...>
two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string
You can find more about jqXHR in documentation. If you want to use the response string, consider opting for .success method. You may have to explicitly provide .contentType
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With