aln447
aln447

Reputation: 1011

Ajax JSONP fires success function despite it returning 404 & 422

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.

Upvotes: 0

Views: 308

Answers (1)

nyedidikeke
nyedidikeke

Reputation: 7658

This should help you address the challenge you are facing so as to meet your intended objective:

<script>
    var host = 'https://api.twitch.tv/kraken/channels/',
        channels = [
            "ESL_SC2",
            "OgamingSC2",
            "cretetion",
            "freecodecamp",
            "storbeck",
            "habathcx",
            "RobotCaleb",
            "noobs2ninjas",
            "brunofin",
            "comster404"
        ];

    channels.forEach(function(channel) {

        console.log(channel);

        $.ajax({
            type: 'GET',
            url: host + channel,
            contentType: 'application/json',
            xhrFields: {
                withCredentials: false
            },
            headers: {
            },
            success: function(data) {
                console.log(data);
                console.log('Logo: ' + data.logo);
                console.log('Display name: ' + data.display_name);
                console.log('Game: ' + data.game);
                console.log('URL: ' + data.url);
            },
            error: function(data) {
                // Not Found (404)
                if (data.readyState == 4 && data.status == 404) {
                    console.log(data);
                    console.log('Error: ' + data.responseJSON['error']);
                    console.log('Status: ' + data.responseJSON['status']);
                    console.log('Message: ' + data.responseJSON['message']);
                }
                // Unprocessable Entity (422)
                if (data.readyState == 4 && data.status == 422) {
                    console.log(data);
                    console.log('Error: ' + data.responseJSON['error']);
                    console.log('Status: ' + data.responseJSON['status']);
                    console.log('Message: ' + data.responseJSON['message']);
                }
            }
        });
    });
</script>

Upvotes: 1

Related Questions