0

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.

Olivier Boissé
  • 15,834
  • 6
  • 38
  • 56
Clebson
  • 296
  • 1
  • 12
  • you may take a look [here](https://stackoverflow.com/questions/13883813/ajax-not-updating-variable) or... – gaetanoM Sep 04 '18 at 17:07
  • So you have issues with how you are using `i` where when the callback executes, the value of `i` is wrong. And the other issue is you try to order a pizza and eat it before it gets delivered. The loop finishes before the Ajax calls are done so you log before it is complete. – epascarello Sep 04 '18 at 17:09
  • you code is `asynchronous` so `valuePlan` will not hold the result values immediadly but at the ends of the ajax calls, you should definitly use `Promise` to handle this type of scenario – Olivier Boissé Sep 04 '18 at 17:09

0 Answers0