Question: 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.

One potential solution would be to abort all AJAX requests on page unload, but the error handler is called before unload, so this doesn't seem possible.

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 I don't want this handling to be called when a user navigates away from the page.

How do I do this?

--

(Also strange: When navigating away from a page, the error handler says that the textStatus parameter is "error", the same it throws when receiving a 500/bad request.)

Answer: 
In the error callback or [$.ajax](http://docs.jquery.com/Ajax/jQuery.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);
    }
  }
});

```

**Edit:**
To tell the difference between a connection broken by the browser and the case where the server is down (jasonmerino's comment):

> 
> On unload the xhr.readyState should be 0, where for a non responsive
>  server the xhr.readyState should be 4.
> 
> 
>
If you make use of jQuery functions such as `$.get`, `$.post`, `$.ajax`... then you can use the parameter `text_status` to check what type of fail is:

```
request = $.get('test.html', function(data){
    //whatever
}).fail(function(xhr, text_status, error_thrown) {

    if(text_status!== 'abort'){
        console.warn("Error!!");
    }
});

```

From the [jQuery docs](http://api.jquery.com/jquery.ajax/):

> 
> **jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});** An alternative construct to the error callback option, the .fail() method
>  replaces the deprecated .error() method. Refer to deferred.fail() for
>  implementation details.
> 
> 
>