Reputation: 5291
I have been learning about AJAX and I am a little confused on which order the methods inside an AJAX call are executed. I have seen too many variations. For example
function submitArticle() {
try {
//alert("yaay");
xhr = new XMLHttpRequest();
}
catch(e) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e) {
alert("Your Browser is not Supported");
return false;
}
}
}
var parameters = "postTitle=" + postTitle "&postDes=" + postDes + "&postCont=" + postDes;
xhr.open('POST', '/engine/engine.php', true);
xhr.send(parameters);
xhr.onreadystatechange = function() {
if(this.readyState === 4) {
if(this.status ===200) {
alert(this.responseText);
}
else {
alert("status" + this.status);
}
}
else {
alert("readyState" + this.readyState);
}
}
}
My question is that I have seen code where the open and send methods are placed in a very different spot, like after evaluating the readyState value. Which is the right way to go. I have looked it up on different sites and all i see are jquery tutorials and none of them explained in which order the code will be executed. Sorry if this is a very stupid question or if my code is wrong.
Upvotes: 0
Views: 151
Reputation: 888107
Javascript can only call the onreadystatechange
callback when control returns to the event loop, after your code finishes running.
Therefore, it doesn't matter whether you add the handler before or after sending the request, as long as you add it in the same unit of synchronous execution.
Upvotes: 1