I have been attempting to address AJAX errors using the code below, but unfortunately, it does not seem to be effective.
function ajaxPost(url, data, success, error) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status === 200) {
if (typeof success === "function") {
success(xmlhttp.responseText);
}
}else if([404, 500 , 503, 504 ].indexOf(xmlhttp.status) > -1){
if(typeof error === "function"){
error();
}
}
}
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
xmlhttp.send(JSON.stringify(data));
}
Is there any other status code that I'm missing in [404, 500 , 503, 504 ]
? I am trying to avoid unnecessary libraries and keep my code lightweight by programming everything using native JavaScript. Any assistance would be greatly appreciated.
Although the above function effectively sends data to the server, it fails to trigger an error message when the server is unreachable. Can someone guide me on how to handle this issue?