views:

548

answers:

2

If I navigate away from a page in the middle of an $.ajax() request it fires the error callback. I've tested in Safari and FF with both GET and POST requests.

It has been suggested that one could abort all AJAX requests on page unload but the error handler is actually called first so it doesn't seem possible nor practical.

This is problematic because I want to be able to handle REAL errors such as 500s gracefully on the client side with a polite alert or a modal dialog, but if this is being called when a user navigates away from the page it poses a big problem.

Another strange thing is that the textStatus parameter is "error", the same it throws when receiving a bad request.

Am I missing something?

A: 

The error callback should get a reference to the XHR object, check the status code to see if it's a server error or not?

great_llama
+2  A: 

In the error callback or $.ajax you have three input arguments:

function (XMLHttpRequest, textStatus, errorThrown) {
   this; // options for this ajax request
}

You can check directly the xhr.status to get the HTTP response code, for example:

$.ajax({
  url: "test.html",
  cache: false,
  success: function(html){
    $("#results").append(html);
  },
  error: function (xhr, textStatus) {
    if (xhr.status == 500) {
      alert('Server error: '+ textStatus);
    }
  }
});
CMS
Makes sense, on unload the status = 0, thanks.
Graham