I am a bit confused in the call flow of Ajax, Could some one help me please?
My HTML:
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="myFunction()">Change Content</button>
My JavaScript:
var xmlhttp;
function loadXMLDoc(url, cfunc) {
alert("4");
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
alert("5");
xmlhttp.onreadystatechange = cfunc;
alert("6");
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function myFunction() {
alert("1");
loadXMLDoc("ajax_info.txt", function() {
alert("2");
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert("3");
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
});
}
According to me the Alert box sequence should be
1 2 3 4 5 6
But it is
1456222223
Could some one please explain me why is the function being called 1'st. I was in the impression untill the parameter values are ready the function cannot be called.
loadXMLDoc(...)
is a normal function call.
It executes immediately.
The callback that you pass it (containing alert("2")
) is only executed when something calls it; namely, when the XMLHTTPRequest raises onreadystatechanged.
onreadystatechanged fires multiple times for different state changes, as you can see in the readyState
property.
Because, after firing the first alert, you're immediately invoking loadXMLDoc
, and passing it the anonymous function (which contains the alerts "2" and "3". Note you're not executing this function; just passing a reference to it, so loadXMLDoc
can execute it later.
So that explains why you see "1 4 5 6" first.
xmlhttp.onreadystatechange = cfunc;
sets the anonymous function we passed to loadXMLDoc
as the onreadystatechange
handler. onreadystatechange
is executed multiple times during an AJAX request; each time the browser determines the state of the request has changed (note that the readyState
value for the AJAX request won't necessarily change each time this happens).
This explains why you see "2" being outputted multiple times.
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert("3");
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
Inside the onreadystatechange
handler, you're checking whether the readyState
is 4
and the status
is 200. A readyState
of 4 means the request has finished, and the check of whether status == 200
checks the HTTP response code.
This is why you see "3" last; because it's only executed when the request completes (because of the conditions in the if
statement).
For more information, you might want to see the MDC article on making AJAX Requests.