jqueryajaxresponsetext

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);
  });

Solution

  • 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!