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.

3
  • you may take a look here or... Commented Sep 4, 2018 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. Commented Sep 4, 2018 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 Commented Sep 4, 2018 at 17:09

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.