0

Wanted to ask why in this piece of code all the .ajax results get crammed into the last div?

$(document).ready(function() {
  var nicks = ["com2ususa", "ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
  for (var i = 0; i < nicks.length; i++) {
    var ni = nicks[i];
    $("body").append("<div id=" + ni + "></div>");
    $.ajax({
      url: "https://wind-bow.glitch.me/twitch-api/users/" + ni,
      success: function(result) {
        $("#" + ni).append("<img width='50px' src='" + result.logo + "'' />");
        $("#" + ni).append(result.display_name);
      }
    });
  };

});
charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • Because ajax is **asynchronous**. The loop is probably completed before the results return for the requests at which point `ni` is the last item in array. Use a closure loop as in the duplicate link above – charlietfl Oct 07 '17 at 22:47
  • Simple closure alternative is use `$.each()` instead of `for()` loop – charlietfl Oct 07 '17 at 22:50
  • @charlietfl thank you a lot! `$.each()` worked for me in the end, but I worked through the example also, was most helpful! – LeighEnne Oct 08 '17 at 05:14

0 Answers0