Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ajax success function is printing [object Object] instead of plain text. Why?

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?

like image 660
doniyor Avatar asked Jun 22 '12 12:06

doniyor


People also ask

Why is ajax success not working?

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.

What is the use of success function in ajax?

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.

What type of object does ajax return?

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.

Is ajax successful deprecated?

Yes, it is deprecated in jQuery 1.8 onwards.


3 Answers

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)

like image 122
Waltzy Avatar answered Oct 29 '22 23:10

Waltzy


add dataType: "text" and change complete() with success()

function ajaxsubmit(){
    $.ajax({
        url: "/update",
        type: "POST",
        dataType: "html"
    }).success(function(data) {
          $('#result').html(data);
      });
    }
like image 39
Cristi Pufu Avatar answered Oct 29 '22 22:10

Cristi Pufu


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

like image 25
friendzis Avatar answered Oct 30 '22 00:10

friendzis