javascript – Jquery get data on XHR error – Education Career Blog

If I make a jquery AJAX request which is succesful I get back my JSON data. However, If I make a request and I get somthing other than a 200 response code back, I cannot get back the data in the Jquery call back. I need the data as it has a description about the data.

success: function (data, tst, xhr) {
    $.log('XHR OK');
},
error: function (xhr, tst, err) {
    $.log('XHR ERROR ' + XMLHttpRequest.status);
},

Any ideas?

Thanks

,

In the:

error: function (xhr, tst, err) {
    $.log('XHR ERROR ' + XMLHttpRequest.status);
},

you can use

error: function (XMLHttpRequest, textStatus, errorThrown) {
    $.log('XHR ERROR ' + XMLHttpRequest.status);
    return JSON.parse(XMLHttpRequest.responseText);
},

to get the JSON response in in event of an error.

XMLHttpRequest.responseText

Cheers.

,

Try the jQuery JSONP plugin. It adds an error callback to a JSON request like so:

$.jsonp({   
    url: "Your URL",
    data: {data: "Some Data"},
    dataType: 'jsonp',
    timeout: 2000,
    success: function(data, status) {
        // Do something with data here
    },
    error: function(xhr, text_status){
        // Handle the server error
    }
});

It does this using a timeout to wait for the server. Unfortunately, there is no other way of telling if the server response with something other than a 200 response.

Leave a Comment