0

I have a function that uses a very large for loop, but when I check j's value inside the AJAX success call, it's at 6 (console.log(j) = 6 6 6 6 6 6). If I put console.log(j) before the success function, it properly shows 0 1 2 3 4 5. Can anyone give me any pointers as to why this is happening or what I'm missing?

function loadInfo() {
  var knuckles = "";
  for (var i = 1; i < channels.length; i++) {
    knuckles += "&login=" + channels[i];
  }
  $.ajax({
    url: url1 + channels[0] + knuckles,
    type: "GET",
    headers: {
      "Client-ID": "XXXXX"
    },
    success: function (json) {
      for (var j = 0; j < channels.length; j++) {
        console.log(j); // Here is where j has the right values
        $.ajax({
          url: url2 + json.data[j].login,
          type: "GET",
          headers: {
            "Client-ID": "aa20kjc6z0zwwogqpz3wqn3245qzc9"
          },
          success: function (json2) {
            console.log(j); // Here is where j has the wrong values
            var sonic;
            if (json2.stream != null) {
              sonic =
                json2.stream.game +
                "</div>" +
                '<div class="info">' +
                "Apple" +
                "</div>";
            } else {
              sonic =
                '<span class="offlineText">Offline</span>' +
                "</div>" +
                '<div class="info">' +
                "Not currently streaming" +
                "</div>";
            }
            $("#streamerInfo").append(
              streamerBoxStart +
              '<div class="icon" style="background-image: url(' +
              json.data[j].profile_image_url +
              '); background-size: cover;">' +
              "</div>" +
              '<div class="nameGame">' +
              json.data[j].display_name +
              " ★ " +
              " " +
              sonic
            );
          }
        });
      }
    }
  });
}

Is it a variable scope thing, loop thing, something I'm completely missing? (Note: this is only a function of my code, other stuff is defined above/below it in the actual code).

1 Answers1

0

Folowing this example: JavaScript closure inside loops – simple practical example

Enclosuring the j value.

function loadInfo() {
  $.ajax({
      success: function (json) {
      for (var j = 0; j < channels.length; j++) {
        console.log(j); // Here is where j has the right values
        (function(j) { // Add this line
            $.ajax({
              success: function (json2) {
                console.log(j); // Here is where j also has the right values
              }
           });
        )(j); // Add this line
    }
  });
}
lmarqs
  • 1,469
  • 13
  • 16