Why is responseText undefined here?

theclarkofben picture theclarkofben · Sep 29, 2015 · Viewed 23.7k times · Source
$.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);
  });

Answer

Magus picture Magus · Sep 29, 2015

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.