After researching similar questions on SO without finding a satisfactory answer, I encountered an issue with synchronous AJAX calls in my HTML/JavaScript page. Mozilla has deprecated some functionality related to synchronous requests, making it necessary for me to adapt my code to handle asynchronous requests better.
In response to this challenge, I have attempted to modify a generic "make web request" function that my application utilizes. However, my current approach is not yielding the desired results.
var webResponse = null;
function webCall(action, type, xmlBodyString) {
console.log("In webCall with " + type + ": " + action);
webResponse = null;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4)
{
if (xmlhttp.status == 200) {
webResponse = xmlhttp.responseXML;
} else {
var statusTxt = xmlhttp.statusText;
if (statusTxt == null || statusTxt.length == 0) {
statusTxt = "An Unknown Error Occurred";
}
throw "ERROR " + xmlhttp.status + ":" + statusTxt;
}
}
}
xmlhttp.open(type, action, true);
if (xmlBodyString == null) {
xmlhttp.send();
} else {
xmlhttp.setRequestHeader("Content-Type", "text/xml");
xmlhttp.send(xmlBodyString);
}
for (var i = 0; i < 20; i++) {
if (webResponse != null) {
break;
}
window.setTimeout(nop, 250);
}
if (webResponse == null) {
throw "Waited 5 seconds for a response, and didn't get one.";
}
console.log("Responding with " + webResponse);
return webResponse;
}
function nop() {
}
Despite setting up a mechanism to wait a maximum of 5 seconds for a response, the code exits prematurely instead of actually waiting. Even when tested in a fiddle, the issue persists. http://jsfiddle.net/Z29M5/
I am seeking assistance in resolving this discrepancy. Any help would be greatly appreciated.