I'm working through the Freecodecamp Twitch API project and I'm unable to get the API data to display correct. The logo, channel and status comes back as undefined.
I know the API is working definitely. Must be something wrong in the way I've written in the code, but can't figure out what.
Here's my code:
$(document).ready(function() {
var users = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
for (i=0; i<users.length; i++) {
var url="https://api.twitch.tv/kraken/channels/" + users[i];
var logo;
var channel;
var status;
$.ajax ({
type: 'GET',
url: url,
headers: {
'Client-ID': 'hw8qejm816w6tjk88fdhfjz1wxpypm'
},
success: function(data) {
logo = data.logo;
channel = data.name;
}
});
var url2 = "https://api.twitch.tv/kraken/streams/" + users[i];
$.ajax ({
type: 'GET',
url: url2,
headers: {
'Client-ID': 'hw8qejm816w6tjk88fdhfjz1wxpypm'
},
success: function(data2) {
if (data2.stream == null) {
status = "Offline";
} else {
status = "Online";
};
}
});
$("#channelInfo").prepend("<div class='row'><div class='col-xs-4'><img src="+logo+"></div><div class='col-xs-4'>"+channel+"</div><div class='col-xs-4'>"+status+"</div>")
};
});
Here's a link to my codepen: http://codepen.io/drhectapus/pen/VPNQJa?editors=1011
Any help would be greatly appreciated.
Because AJAX is asynchronous by default, your last line is getting executed before your ajax request is finished. You should have your post-call results inside your success: function(data)
area, as follows. Note that I added async:false
to your ajax calls so that the inner request would happen in order, which will keep your objects synchronized:
$(document).ready(function() {
var users = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
for (i=0; i<users.length; i++) {
var url="https://api.twitch.tv/kraken/channels/" + users[i];
var user = users[i];
var logo;
var channel;
$.ajax ({
type: 'GET',
url: url,
async: false,
headers: {
'Client-ID': 'hw8qejm816w6tjk88fdhfjz1wxpypm'
},
success: function(data) {
logo = data.logo;
channel = data.name;
var url2 = "https://api.twitch.tv/kraken/streams/" + user;
$.ajax ({
type: 'GET',
async: false,
url: url2,
headers: {
'Client-ID': 'hw8qejm816w6tjk88fdhfjz1wxpypm'
},
success: function(data) {
if (data.stream == null) {
status = "Offline";
} else {
status = "Online";
};
$("#channelInfo").append("<div class='row'><div class='col-xs-4'><img src="+logo+"></div><div class='col-xs-4'>"+channel+"</div><div class='col-xs-4'>"+status+"</div></div>");
}
});
}
});
};
});