hayley
hayley

Reputation: 406

The jqXHR object returned by the ajax call

Either the success event or the error event will get the returned jqXHR object, but I can only access the jqXHR object in the error event.

    $.ajax({
       type: 'POST',
       url:'https://fakeurl',
       data: formData,
       contentType: 'application/x-www-form-urlencoded',                     
       dataType: 'json',
       success: function(textStatus, jqXHR) {
           alert('textStatus: ' + textStatus + ' jqXHR.status: ' + jqXHR.status);
     },error: function(jqXHR) {
       console.log('jqXHR.status: ' + jqXHR.status);
     }
   });

The output in error event got jqXHR.status: 0. And the output in success event is textStatus: [object Object] jqXHR.status: undefined.

Upvotes: 2

Views: 2191

Answers (2)

Hindreen
Hindreen

Reputation: 98

if you want to get back the submitted data, the first argument of success function is the submitted data and the second is the textStatus, the third one for jqXHR which that has all the properties of the response object

$.ajax({
   type: 'POST',
   url:'https://fakeURL',
   data: formData,
   contentType: 'application/x-www-form-urlencoded',
   dataType: 'json',
   success: function(data, textStatus, jqXHR) {
      alert('textStatus: ' + textStatus + ' jqXHR: ' + jqXHR.status);
 },error: function(error) {
   console.log('error.status: ' + error.status);
 }
});

Upvotes: -1

Sam Gomena
Sam Gomena

Reputation: 1479

From the jQuery ajax docs:

success

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

So, if you want to access the jqXHR object in the success callback, you'll need to define three parameters for the function to accept like so:

success: function(data, textStatus, jqXHR) {
           alert('data: ' + data + 'textStatus: ' + textStatus + ' jqXHR.status: ' + jqXHR.status);

Upvotes: 2

Related Questions