Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if Ajax Request had failed in JavaScript

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!

like image 694
Progo Avatar asked Apr 08 '14 01:04

Progo


2 Answers

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

like image 71
Netorica Avatar answered Nov 13 '22 03:11

Netorica


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.

like image 25
Jayesh Chandrapal Avatar answered Nov 13 '22 05:11

Jayesh Chandrapal