While designing a error handling mechanism for AJAX script on my website, I found that the only status code that was returned, by the server, in the event of a error was 0 (or “undefined”). Even when I intentionally created a 404 error by requesting a non-existent file, the only error code that was returned by the server was 0. I believe that this problem is caused by my web-host’s server (www.000webhost.com) when it redirects 404 errors to http://error404.000webhost.com/? however, I need to find a way to get a proper error code from the server’s response in order to deliver feedback to the user on what went wrong… So my question is: how do I make the server return the proper status code, or if that is not the problem: what is wrong with my code?
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
alert(xmlhttp.status); //this alert box shows 200 normally, but during a error only shows 0
if (xmlhttp.status==200) { // 200 = OK, process result
//stuff for processing the result (when there is no error)
}
else { // error handling (creates a jgrowl notification showing the status code)
$('#jGrowl-container').jGrowl('AJAX Error Code: ' + xmlhttp.status', {sticky: true, theme: 'error'});
}
}
}
xmlhttp.open("POST", "process.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("&s="+ScoutID + "&pw="+pword + "&rt="+RequestType + RequestText);
}
There could be different reasons why you are NOT getting proper http-status codes in response.
Check with your hosting provider whether they are handling or have customized the web server for this. You can check it in their control panel or ask their helpdesk.
Your server is redirecting in case of 404 which may not let the browser track it as 404 but instead a 302 or 303 (redirection). Few hosting companies do that.
Also I noticed that you are using jQuery already so why not use it for your ajax calls as well. It works well. You can check it out at http://api.jquery.com/category/ajax/