Twitch API Project issue

https://codepen.io/Krimlen/pen/EvPOEg

here’s my project, I’m using to ajax requests

one to load all the streams

and another one to get the online stream information

as none of the APIs has information about both online and offline streams together

so I have successfully loaded all streams with their names and logos

I want to do changes to the stream div (add the status, change background color to green) if the stream is online

here’s what I’ve tried

streamers array

var streamer = ["Thulz","ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "habathcx", "RobotCaleb", "noobs2ninjas","Rakin"];

for loop fetching every streamer, first ajax for fetching every streamer and putting them in a div each, second one is where I’m struggling

	for(i=0;i<streamer.length;i++){
		$.ajax({
		url: "https://wind-bow.glitch.me/twitch-api/channels/"+streamer[i],
		success: function(response) {
			
		$("#result").append("<div class='row streams'><div class='col-12 imag'><img src='"+response.logo+"' alt='"+response.name+"' height='75' width='75'><div class='texts'>"+response.name+"<p id='"+response.name+"'></p></div></div></div>");			
	}});//first AJAX
		
		$.ajax({//second ajax
		url: "https://wind-bow.glitch.me/twitch-api/streams/"+streamer[i],
		success: function(online) {
			if(online.stream !== null){
				console.log(online.stream.channel.status);
			}
		}//response success
				});
		
	}//streamer for loop

what I’ve tried:

giving a unique #id to every streamer and then append the status and perform the css changes to the streamers the second request gets

$("#"+streamer[i]).append(online.stream.channel.status);

or

var sname= online.stream.channel.name;
$("#"+sname).append(online.stream.channel.status);

none worked, help!

The problem you are having is with the first A in AJAX. While you are making asynchronous calls to the API and waiting for the responses, your loop just continues with nothing set to hold the data when it arrives. What you need to do is store the results of your AJAX calls in variables, and when both variables have successfully acquired their data, do something with that data:

var a = $.ajax({ . . . }); //first AJAX
var b = $.ajax({ . . . }); //second AJAX

$.when(a, b).done(function(channelData, streamData) { . . . });

The $.when().done() will keep track of the a and b variables for each call in the loop and only proceed when both have arrived. Just put your append() code in there and see if that does the trick. Also, channelData and streamData just refer to a and b respectively. You don’t have to use those variable names, that’s just what I used for my Twitch app for clarity :slight_smile:

1 Like