I am starting out with Javascript and Ajax, and I need to implement a retry mechanism that tries 3 times if the ajax response is not 200.
Ajax Function -
function fireAndForget(strURL) {
log("will attempt to invoke... [ " + strURL + " ]");
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
} // IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
}
self.xmlHttpReq.open('GET', strURL, true);
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
if(self.xmlHttpReq.status == 200) {
log("received JSON response : [" + self.xmlHttpReq.responseText + "]");
var resObj = parseJSON(self.xmlHttpReq.responseText);
if("handled" in resObj) {
if(resObj.handled) {
if("success" in resObj) {
if(resObj.success) {
// DO NOTHING
} else {
if(resObj.message) {
alert(resObj.message);
}
}
}
}
} else {
log("auth update notification was not handled. response : [" + self.xmlHttpReq.responseText + "]");
}
} else {
// unable to contact the auth update listener
alert("<%=pNotifyFailedMsg%>");
log("unable to contact listener URL @ [" + strURL + "]");
}
}
};
// fire a get request with the SSO information
self.xmlHttpReq.send(null);
//alert("sent url : [" + strURL +"]");
}
Need to include retry logic for
if(self.xmlHttpReq.status == 200) {
log("received JSON response : [" + self.xmlHttpReq.responseText + "]");
var resObj = parseJSON(self.xmlHttpReq.responseText);
if("handled" in resObj) {
if(resObj.handled) {
if("success" in resObj) {
if(resObj.success) {
// DO NOTHING
} else {
if(resObj.message) {
alert(resObj.message);
}
}
}
}
} else {
log("auth update notification was not handled. response : [" + self.xmlHttpReq.responseText + "]");
}
} else {
// unable to contact the auth update listener
alert("<%=pNotifyFailedMsg%>");
log("unable to contact listener URL @ [" + strURL + "]");
}
I have tried using loops and other solutions in the else part of the above code, but it didn't work. Can someone please provide guidance on the best approach for implementing a retry in such cases?
The alert in the else part should only be shown after 3 retry attempts.