$.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);
});
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With