I’m having trouble with a synchronous AJAX request.
I am creating a web application where there are many AJAX requests called in sequence which should be returned in strict order. Rather than putting every succeeding request in the readystatechange event handler of the last request, I decided to simply call them synchronously.
However, in the following code, alert() is invoked before adding the response to the DOM.
window.addEventListener("load", main, false);
function main (e) {
// Sending synchronous request
var request = new XMLHttpRequest();
request.open("GET", fileName, false);
request.overrideMimeType("text/xml");
request.send(null);
// Receiving response
var response = request.responseXML;
// Changing XML Tree to corresponding XHTML Tree
response = XMLtoXHTML(response);
//Adding response to the body
document.body.appendChild(response);
// Calling alert
alert("Hello World");
}
The response gets in fact successfully added to the DOM, but only after clicking OK on the alert message. When I do a walkthrough using Safari’s Script Debugging features, the response does get added to the DOM before calling alert().
Any suggestions?
NB: I left out other requests.
I guess it actually does get added, you just don’t see the changes before JS returns control back to the browser, i.e. until alert window is closed. If you cannot do an async request (which I would suggest first), you could at least make dom changes in a separate
setTimeouted “thread”.