0

I have 8 identical functions utilizing authenticated AJAX calls with Postman and editing html elements. In an attempt to really streamline my code, I have attempted to make all 8 postman calls in a for LOOP. The calls are authenticating without issue it seems but my global arrays are not passing in to the $.ajax call, making me unable to actually use the response from each call.

If I need to make all calls separately, then that's what I need to do, but wanted to check here before I gave up.

var x1 = [postman headers]
var x2 = [html selectors]
//Master for loop
var main = function(){
  for (var i = 0; i < x1.length; i++){
    var x3 = [url identifiers];
    var settings = {
      "async": true,
      "crossDomain": true,
      "url": "my_url"+x3[i], //works without issue
      "method": "GET",
      "headers": {
        "authorization": "Basic x",
        "cache-control": "no-cache",
        "postman-token": x1[i] //works without issue
      }
    }
    $.ajax(settings).done(function loadData (response) {
      var myData = response[x3[i]]; //is undefined console errors on this line
      $(x2).html(myData); //is undefined console will error on this line as well
      console.log(myData);
    });
  } // End FOR loop
} // End function`
Jonathan
  • 25
  • 4

1 Answers1

0

Its a scoping problem:

start ajax call
loop goes on i is increased
ajax finished but i isnt at the right position

You need to create a closure:

for(i=0;i<length;i++){
 (function(i){
   //your code
 })(i);
 }
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151