Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is responseText undefined here?

$.ajax({
  url: 'http://jsonplaceholder.typicode.com/posts/1',
  method: 'GET',
}).done(function(data){
  console.log(data);
  console.log(data.responseText);
});

Can anyone help me understand why console.log(data.responseText); is returning undefined?

http://clarkben.com/ajaxtesting/

Edit: OK so it looks like data is not a jqXHR object. If a assign the whole $.ajax statement to a variable then that variable is a jqXHR object so it can be accessed that way. I'm not sure why the data passed in to the function that is part of .done is not a jqXHR object though.

var theRequest = $.ajax({
    url: 'http://jsonplaceholder.typicode.com/posts/1',
    method: 'GET',
}).done(function(data){
        console.log(data);
        console.log(theRequest.responseText);
  });
like image 485
theclarkofben Avatar asked Sep 29 '15 15:09

theclarkofben


2 Answers

By default, jQUery try to guess the type of a response. If the headers of the response is application/json, data will be a javascript object. If this is something like text/html or text/plain, data will be a simple string containing the body of the response.

And data.responseText is obviously undefined if you call that on a string (or a javascript object with no property responseText)

See the jQuery ajax documentation : http://api.jquery.com/jquery.ajax/

jqXHR.done(function( data, textStatus, jqXHR ) {});

The first parameter is data. If you want the jqXHR, this is the third parameter.

like image 53
Magus Avatar answered Oct 05 '22 23:10

Magus


OK so eventually I found the answer in the jqXHR documentation:

jqXHR.done(function( data, textStatus, jqXHR ) {});

An alternative construct to the success callback option, the .done() method replaces the deprecated jqXHR.success() method. Refer to deferred.done() for implementation details.

So now the below code works:

$.ajax({
    url: 'http://jsonplaceholder.typicode.com/posts/1',
    method: 'GET',
}).done(function(data, textStatus, jqXHR){
        console.log(data);
        console.log(jqXHR.responseText);
  });

Got there in the end!

like image 35
theclarkofben Avatar answered Oct 05 '22 21:10

theclarkofben