jqueryajaxresponsetext

Puzzled as to why .done() not passing in the jqXHR object?


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

Is my understanding correct that the data that is passed in to the function within the .done() method should be the jqXHR object that is returned from the $.ajax() request?

I thought the below code would work but it doesn't because data does not have a responseText property, which I thought it would because I thought it should be the jqXHR object returned from the $.ajax() request?

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

Solution

  • Is my understanding correct that the data that is passed in to the function within the .done() method should be the jqXHR object that is returned from the $.ajax() request?

    No, data will be the data returned by the request. From the 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.

    ...which I'll grant is less than thorough. :-) But note the three arguments in the function signature shown: data, textStatus, and jqXHR. These are the same as for the success function if you use it in the options, so the documentation for them is useful:

    Type: Function( Anything data, String textStatus, jqXHR jqXHR )

    A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter or the dataFilter callback function, if specified; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object.