I am trying to make multiple requests on the server within a loop for
. I found some tips here and implemented the suggested solution. However, it does not seem to work.
var valuePlan = [];
function getValue(id) {
var f = (function(){
var xhr = [], i;
for(i = 0; i < id.length; i++){ //for loop
(function(i){
xhr[i] = new XMLHttpRequest();
url = "get.php?id=" + id[i] + "&for=monthly";
xhr[i].open("GET", url, true);
xhr[i].onreadystatechange = function(){
if (xhr[i].readyState === 4 && xhr[i].status === 200){
console.log('Response from request ' + i + ' [ ' + xhr[i].responseText + ']');
valuePlan.push(xhr[i].responseText.replace(".", ","));
}
};
xhr[i].send();
})(i);
}
})();
};
getValue([48,52,50]);
console.log(valuePlan[0]);
The problem that when I use console.log(valuePlan[0]);
in console it returns undefined
, and if it uses console.log(valuePlan);
returns the arrays
with the correct values. Can you understand that?
The variable is already defined as global, and even then I can not fetch the individual values of it.