I have a program displaying information about certain Twitch streamers with their names located in an array (Yes, it's from FreeCodeCamp) and have been stuck with one small issue:
I have and $.ajax which could catch a failure thanks to the ajax timeout.
Funny thing is in this example ajax not only does not fire the error function but seems to give it a success, resulting in errors and me getting this in the console:
GET https://api.twitch.tv/kraken/channels/brunofin 422 (Unprocessable Entity)
GET https://api.twitch.tv/kraken/channels/comster404 404 (Not Found)
Here is the jquery used for the project:
var channels = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas", "brunofin", "comster404"];
$(document).ready(function() {
appendStreams(0);
});
function appendStreams(arg) {
//arg == 0 - all streams
//arg == 1 - only online
//arg == 2 - only offline
var sLogo, sName, sLink, sGame; //base table values, used later to append everything
var toAppend = false; //a greenlight variable telling when is it ok to append a div
var success; //a greenlight variable informing about 404 for jsonp
$("#channels *").remove(); //Each call should empty all the slots
channels.forEach(function(value) {
success = false;
$.ajax({
url: 'https://api.twitch.tv/kraken/streams/' + value + '?callback=?',
type: "GET",
dataType: 'jsonp',
timeout: 5000,
success: function(data) {
console.log("success for " + value);
if (data.stream != null && (arg == 0 || arg == 1)) {
//capture data only of players who are now streaming
sLogo = data.stream.channel.logo;
sName = data.stream.channel.display_name;
sGame = data.stream.game;
sLink = data.stream.channel.url;
toAppend = true;
} else if (data.stream == null && (arg == 0 || arg == 2)) {
//due to the lack of data comming from offline streams, a second json call has to be made, to the channel parts of the api
//A non async should be used to retain the data
$.ajax({
async: false,
url: "https://api.twitch.tv/kraken/channels/" + value,
dataType: 'json',
success: function(data2) {
sGame = "Offline";
sLogo = data2.logo;
sName = data2.display_name;
sLink = data2.url;
}
});
toAppend = true;
}
if (toAppend) {
$("#channels").append('<tr><td><img src="' + sLogo + '" alt="channel logo" height="100px"/></td><td><a href="' + sLink + '">' + sName + '</a></td><td>' + sGame + '</td></tr>');
}
toAppend = 0; //reset toAppend
},
error: function() {
console.log(value + "has failed");
}
});
}); //forEach end
}
AND HERE you can find the codepen code itself. I hope everything is commented well enough to be understood
What is causing the issue and how could I fix it? Any help would be great.