I am pretty new to this site. I have a question when working on a XMLHttpRequest which is replicated in a for loop as following:
I don't understand the difference between the following two blocks of code:
function changeForm(i) {
if (selection[i-1] != 0) {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("box"+i).innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("POST", "fetchLineChoice_addData.php", true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("index="+i+"&lc="+selection[i-1]);
} else {
document.getElementById("box"+i).innerHTML = "";
}
}
for (var i = 1 ; i < 4 ; i++) {
changeForm(i);
}
AND
for (var i = 1 ; i < 4 ; i++) {
if (selection[i-1] != 0) {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("box"+i).innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("POST", "fetchLineChoice_addData.php", true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("index="+i+"&lc="+selection[i-1]);
} else {
document.getElementById("box"+i).innerHTML = "";
}
}
I don't really know why the first one works but the second one does not. I have tried to search on the net about closures and came up with these two:
Calling a XMLHttpRequest continuously
JavaScript closure inside loops – simple practical example
From the second question, it was mentioned that the function is bound to a variable i outside the function. I would like to know for the second block of code (that does not work), I would like to know why the content in the for loop is not fully executed before the value of i increases again? What is the flow when the two blocks of code are being executed?
Thank you very much!