Help
cancel
Showing results for 
Search instead for 
Did you mean: 
Copilot Lvl 2
Message 1 of 4

[Javascript] XMLHttpRequest always returns "undefined"

Solved! Go to Solution.

I've created this Twitch chatbot that uses League of Legend's API through a URL in JSON, you can check out more about that in here: https://developer.riotgames.com/apis#league-v4/GET_getLeagueEntriesForSummoner

 

Here is the whole code:

 

const tmi = require("tmi.js");
const fs = require("fs");
const XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;

var channelConfig = require("/home/koryokin/bots/wolyotwitchbot/data/ChannelConfig.json");
var channelInfo = require("/home/koryokin/bots/wolyotwitchbot/data/ChannelInfo.json");
var logConfig = require("/home/koryokin/bots/wolyotwitchbot/data/LogConfig.json");
var leagueConfig = require("/home/koryokin/bots/wolyotwitchbot/data/LeagueConfig.json");

var client = new tmi.client(logConfig);

client.connect().then(async data => {
    await update();
}).catch(err => {
    throw err;
});

async function update(){
    client.on("subscription", (channel, user, method, message, userstate) => {
        client.action(channel, user["display-name"] + ", just subscribed. Thank You! <3")
    });
    client.on("resub", (channel, user, months, message, userstate, method) => {
        client.action(channel, user["display-name"] + ", just re-subscribed for " + months + " months. Thank You! <3")
    });
    client.on("hosted", (channel, username, viewers, autohost) => {
        if(viewers >= 10){
            client.action(channel, user["display-name"] + ", hosted with " + viewers + " viewers. Thank You! <3")
        }
    });
    
    client.on("chat", (channel, user, message, self) => {
        if(!self){
            readInput(channel, user, message);
            messageCounter(channel, message);
        }
    })
}

function readInput(channel, user, input){
    if(input.startsWith("!")){
        var userInput = input.slice(1, input.length);

        if(Object.keys(channelConfig[channel].InputOutput).includes(userInput))
        {
            client.say(channel, "@" + user["display-name"] + " " + channelConfig[channel].InputOutput[userInput]);
        }
        else if(userInput == "help")
        {
            var allCommands = Object.keys(channelConfig[channel].InputOutput);
            var output = "";

            for(var i = 0; i < allCommands.length; i++){
                output += JSON.stringify(allCommands[i]);

                if(i != allCommands.length - 1)
                    output += ", ";
            }
            output += ".";
            client.whisper(user["display-name"], "Commands: " + output);
        }
        else if(userInput == "rank")
        {
            var allSummoners = Object.values(leagueConfig.Summoners);

            for (var i = 0; i < allSummoners.length; i++) {
                var leagueURL = "https://br1.api.riotgames.com/lol/league/v4/entries/by-summoner/" + allSummoners[i] + "?api_key=" + leagueConfig.APIKey;

                getJSON(leagueURL, function(data){
                    client.say(channel, "@" + user["display-name"] + " " + data);
                });
            }
        }
        else
        {
            client.whisper(user["display-name"], "'" + userInput + "' is not a command.");
        }
    }
}

function messageCounter(channel, userInput){
    if(Object.keys(channelInfo[channel].Messages).includes(userInput))
    {
        channelInfo[channel].Messages[userInput]++;
        fs.writeFile("/home/koryokin/bots/wolyotwitchbot/data/ChannelInfo.json", JSON.stringify(channelInfo), (err) => {
            if(err != null) throw err;
        });

        client.say(channel, userInput + " [" + JSON.stringify(channelInfo[channel].Messages[userInput]) + "]");
    }
}

function getJSON(url, callback) {
    var xhr = new XMLHttpRequest();

    xhr.open("GET", url, true);
    xhr.responseType = "json";

    xhr.onload = () => {
        if (xhr.status === 200)
            callback(xhr.response);
    };

    xhr.send();
};

All that code is running inside a VPS with Forever.

 

What happens is that the getJSON function always returns "undefined" no matter what URL it's used.

 

At first, I thought it could've something to do with XHR running in Async, but as far as I know, my code is taking care of that with no problem. I also tried running the code in a LocalHost with Node.js on my computer just to see if the problem would be related to the VPS being on Linux instead of Windows, but the problem stood exactly the same.

Keep in mind that the variable LeagueURL and the local JSON files are NOT the problems, so you can get that out of the way.

 

Important parts of the code that are most likely related to the problem:

 

Creating the getJSON function:

function getJSON(url, callback) {
    var xhr = new XMLHttpRequest();

    xhr.open("GET", url, true);
    xhr.responseType = "json";

    xhr.onload = () => {
        if (xhr.status === 200)
            callback(xhr.response);
    };

    xhr.send();
};

Using the getJSON function:

            var allSummoners = Object.values(leagueConfig.Summoners);

            for (var i = 0; i < allSummoners.length; i++) {
                var leagueURL = "https://br1.api.riotgames.com/lol/league/v4/entries/by-summoner/" + allSummoners[i] + "?api_key=" + leagueConfig.APIKey;

                getJSON(leagueURL, function(data){
                    client.say(channel, "@" + user["display-name"] + " " + data);
                });
            }

 

3 Replies
Pilot Lvl 2
Message 2 of 4

Re: [Javascript] XMLHttpRequest always returns "undefined"

Hi @KoryoKin !

 

Have you tried searching the problem up yet? If not, Mosh Hamedani has a short course about it, and there's something about undefined there. JavaBrains has something about that as well.

 

By the way, all the links in here are YouTube links 😉.

 

- Zoe K.

Solution
Copilot Lvl 2
Message 3 of 4

Re: [Javascript] XMLHttpRequest always returns "undefined"

Hello, @infinite-dreams .

 

I couldn't find the solution to the problem, however, I found a different approach to what I wanted to do.

I decided to throw the whole XMLHttpRequest away and tried using fetch. It worked.

Here is the code solution:

 

var getJSON = (url, callback) => {
    fetch(url).then(async response => {
        callback(await response.json());
    }).catch(err => {
        throw err;
    });
}

 

 

Pilot Lvl 2
Message 4 of 4

Re: [Javascript] XMLHttpRequest always returns "undefined"

Awesome! I'll keep that in mind the next time I do JavaScript 😃.