views:

216

answers:

3

This is the gut of my ajax call.

function ajax(path, requestData, successCallBack, errorCallBack) {
    return $.ajax({
        error: function(xhr, textStatus, errorThrown) 
            ç(xhr, textStatus, errorThrown);
        },
        success: function(json){ 
            successCallBack(json);
        }
    });
}

When there is an ajax call going on and the user clicks on a link on the page, my errorCallBack is invoked. The user navigating away would cause the ajax call to be killed. When there is an error on the server, my errorCallBack callback is also invoked.

Is there a way to differentiate the two?

Thanks!

A: 

Check the xhr object's properties. It should have the HTTP response code in it somewhere.

nickf
+3  A: 

I had the same problem with something I was working on... A 'canceled' $.ajax request (user navigates away / hits stop) xhr.status == 0 instead of 200/404/etc...

gnarf
A: 

Here's is the technique I used to implement gnarf's and nickf's answers:

jQuery throws the error event when the user navigates away from the page either by refreshing, clicking a link, or changing the URL in the browser. You can detect these types of errors by by implementing an error handler for the ajax call, and inspecting the xmlHttpRequest object:

$.ajax({
    /* ajax options omitted */
    error: function (xmlHttpRequest, textStatus, errorThrown) {
         if(xmlHttpRequest.readyState == 0 || xmlHttpRequest.status == 0) 
              return;  // it's not really an error
         else
              // Do normal error handling
});
colbeerhey