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:
$.ajax({         
 type: "POST",         
 url: $(this).data('targetUrl'),         
 cache: false,         
 success: function(data){                 
  //Do something         
 },     
 error:function (xhr, ajaxOptions, thrownError){
        alert(xhr.status);             
  alert(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
  }
});

6 comments:

Vusile Terence Silonda said...

This was very useful to me... The minute I read it, I understood exactly what was causing the problem on my scripts. Thanks.

Ivan Talalaev said...

Many MANY THANKS!!!!!! It was very usefull for my undersdanding ajax.

Anonymous said...

Thanks..I had the same issue

Doug S said...

Whew, thanks! I had the same issue after refactoring some code and couldn't figure out why. I just ranted at myself that "nothing changed". This gave me the much needed kick in the pants to look wider.

Abdeali Chandanwala said...

hi,

it didnt solved my problem ... :(

Krushus Ibarra said...

I had the same problem. With PHP, Javascript and AJAX, I was developing a 3 steps configuration. In 2nd step, I was calling AJAX to perform a task and after completed, automaticaly navigate to the 3rd page, but "0 error undefined" alert showed everytime.
I added a delay inside the function, before AJAX.

here's the code

function myID(){
var iddisp2 = "";
document.getElementById("iddisp2").value=iddisp2;
var datos =iddisp2;

$.ajax({
url: 'core/modules/index/view/dbexecute.php',
dataType: "text",
type: "POST",
data: {datos:datos},
success: function(resp) {
//alert(resp);

},
error: function (xhr, ajaxOptions, thrownError, textStatus) {
alert(xhr.status + " " + thrownError + " " + ajaxOptions+ " " + textStatus);
}
});
esperar(1500);

}


function esperar(millis)
{
var date = new Date();
var curDate = null;

do { curDate = new Date(); }
while(curDate-date < millis);
}