Search code examples
javascriptjqueryjsonriot-games-api

Retrieving a variable from within a function


I am attempting to pull information from the League of Legends API.

To simplify what I am doing, I am attempting to pull information about a user and their previous matches. The problem that I run into is that when I parse a JSON request, it returns a champion ID rather than their name (Ex: 412 rather than "Thresh").

The only solution I can see for this would be to make another JSON request and parse that data for the champion name. Currently what I have looks like this.

$.getJSON(championMasteryPHP, function (json) {
    for (var i = 0; i < 20; i++) {
        var champID = json[i].championId;
        var championInfo = "http://example.com/champInfo.php?summonerid=" + champID;

    $.getJSON(championInfo, function (json2) {
        var champName = json2.name;
    });

    $('#champ').append("<li>"+champID+" - "+champName+"</li>")
    }
});

I'm unable to access the champName variable due to it being nested within the second JSON function.

Is there a better way to do this?


Solution

  • $.getJSON(championMasteryPHP, function (json) {
        for (var i = 0; i < 20; i++) {
            var champID = json[i].championId;
            var championInfo = "http://example.com/champInfo.php?summonerid=" + champID;
    
        $.getJSON(championInfo, function (json2) {
            var champName = json2.name;
            $('#champ').append("<li>"+champID+" - "+champName+"</li>")
        });
        }
    });
    

    Just put it inside the second json request since you need to wait till that request is done anyway.