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!
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With