Question

How can I detect whether an Ajax request failed to load a file.

Here is my code for reference:

var pro = undefined;
var xmlhttp;
if (window.XMLHttpRequest){
    xmlhttp = new XMLHttpRequest();
}
else{
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200){
        pro = JSON.parse(xmlhttp.responseText);
    }
}
xmlhttp.open("GET","data.json",true);
xmlhttp.send();

Please, no jQuery.

Thanks!

Was it helpful?

Solution

you can check if the http status is 500 or more than 500 which means an error occurred in the request http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#5xx_Server_Error

 if (xmlhttp.status >= 500){
    alert('error');
 }

NOTE: you can also consider other http status numbers as you like

OTHER TIPS

onerror callback should be used for handling error, like this:

xmlhttp.onerror = function onError(e) {
    alert("Error " + e.target.status + " occurred while receiving the document.");
}

As far as I know, jQuery library also uses this method. Not sure which all browsers support this, but this surely works in firefox.

What I do is use a global variable I name 'boomerang' (witty I know)

so when you send the request out make boomerang=1 and then on its success make boomerang=0

then at some appropriate time after you send the request out then you can just check if boomerang =1 or =0

you need to check the status code- 4xx and 5xx codes are errors.

here's a list of codes: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

You won't need much more. Do something in the else clause other than the comment.

xmlhttp.onreadystatechange = function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200){
        pro = JSON.parse(xmlhttp.responseText);
    } else {
        if (xmlhttp.readyState==4) {
            // Something failed
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top