730
730

Reputation: 21

"Uncaught TypeError: Cannot read property 'x' of undefined" when trying to get a property from an object

So, I get my list of Steam games in JSON through the Steam Web API. When I try to get a property from the JSON directly through the Chrome console, it's all good. But when I execute the same line in my code, it throws Uncaught TypeError: Cannot read property 'x' of undefined('x' stands for whatever property I try to get).

key = "lotsofrandomnumbersandletters";
id = "steamprofileid";
var gameList = $.getJSON("http://www.corsproxy.com/api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key=" + key + "&steamid=" + id + "&format=json");
var gameCount = gameList.responseJSON.response.game_count;

Upvotes: 0

Views: 1684

Answers (2)

730
730

Reputation: 21

Solved it using Anthony's answer, but declaring gameCount outside of $.getJSON.

Upvotes: 0

Anthony Chu
Anthony Chu

Reputation: 37520

$.getJSON() is asynchronous and you need to access its result in a callback...

$.getJSON("http://www.corsproxy.com/api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key=" 
        + key + "&steamid=" + id + "&format=json", function (gameList) {
    var gameCount = gameList.responseJSON.response.game_count;
});

Upvotes: 2

Related Questions