For-loop with API query

Hi! Could someone help me understand why images come out empty after all the looping is done? It has all the data at the end of the last loop, but comes out empty after the looping is over.

$( document ).ready(function() {
var names = ["ESL_SC2", "OgamingSC2", "cretetion", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
var status =[];
var images = [];

// list of images
for (var i=0; i<names.length;i++){
       $.ajax({url: "https://wind-bow.glitch.me/twitch-api/users/" + names[i], success: function(result){
        status.push(result.logo);

 }}
);

} 
});

I’ve edited your post for readability. When you enter a code block into the forum, remember to precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

markdown_Forums

Also, I have questions like this all the time, if anyone is same lost as me, let’s stay in touch!

Where exactly are you putting data into the images array?

They’re not, but I think I understand what’s happening. Are you checking the status array in the console? That would not show you the contents as you expect.

1 Like

Nowhere at the moment, this was supposed to go to images, but I thought maybe it does not work, because images is a sort of keyword, so it goes to status now.

Thanks! So I cannot actually push anythign to array with my code?

You can, but the issue is viewing the array in the console. Chances are your browser is running console.log(status) before the HTTP calls have finished, so it’s still empty at that point. The larger issue here is that you don’t want to push to an array. Handle everything in your callback function. Check my Codepen above for an example.

I did, it helps a lot! I just wanted to make sure I understand where I have the problem.

Can I ask something else also? The loop generates several separate divs, but why does the ajax function push everything 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);
          }});  };
 
 });
 

The codepen where you can see the result is here: https://codepen.io/Leighenne/pen/NayXQb

Ok, I am a bit of a noob, so I thought a loop will only go onto new step and increment after the previous one is done. Anyway to control for that?

Thanks! I have solved it with jQuery.each in the end.