Getting AJAX response body for use in error callback

jQuery's AJAX error function has the following parameters:

error(XMLHttpRequest, textStatus, errorThrown)

What's the best cross-browser way to get the response body?

Does this work (reliably in all browsers)?

$.ajax({
  error: function(http) {
    alert(http.responseText);
  }
});

Solution 1:

As of jQuery 1.4.1 you should use:

var json = JSON.parse(xhr.responseText);

See http://api.jquery.com/jQuery.parseJSON/.

Solution 2:

For a more recent and general answer (since jquery 1.5), I'd use the jqXHR object:

$.ajax(url).fail(function(jqXHR, textStatus, errorThrown) {
    alert(jqXHR.responseText);
})

Alternatively responseJSON can be used to get the response body already parsed

$.ajax(url).fail(function(jqXHR, textStatus, errorThrown) {
    console.log(jqXHR.responseJSON);
})

Solution 3:

One straightforward usage example with jQuery:

var url = '/';
$.get(url).then(
  function(response) {
      $("#result").html(response);
  },
  function(jqXHR) {
    $("#result").html('Error occurred: '+ jqXHR.statusText + ' ' + jqXHR.status);
  }
); 

This should return the HTML of current website front page.

Then try entering a nonsense URL that doesn't exist and see the error thrown. You should get "404 Not Found" from web server. Test it: JSFiddle here