Tuesday, February 28, 2012

Ajax request returns status 0

Last week our users reported a bug that they got an alert window in their browser showing 0(zero). We traced the problem back to the following JavaScript code:
 type: "POST",         
 url: $(this).data('targetUrl'),         
 cache: false,         
 success: function(data){                 
  //Do something         
 error:function (xhr, ajaxOptions, thrownError){

The alert window shows the following message 0 and ‘undefined’.

We found out that this could happen if the ajax request is getting canceled before it completes. We could reproduce the problem if we triggered the ajax request and then immediately click on a link to navigate away from the page. 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.

We fixed the issue by introducing a global error handler for the ajax call, and inspecting the xmlHttpRequest object:

$(document).ajaxError(function(e, jqxhr, settings, exception) {
  if (jqxhr.readyState == 0 || jqxhr.status == 0) {
    return; //Skip this error