Reputation: 672
How do I access my data from outside the getJSON command?
//LOAD JSON
$.getJSON("users.js", function(data) {
numberOfPieces = data.users.length;
alert("Loaded "+numberOfPieces); // <------WORKS
});
//Select a piece
var pieceSelected = Math.floor(Math.random() * (numberOfPieces));
alert("pieceSelected: "+data.users[pieceSelected].Name); // <------RETURNS "data is not defined"
Thank you!
Upvotes: 0
Views: 80
Reputation: 892
Your issue is that function parameters are scoped to that function and inaccessible outside of the function. By using a variable outside of the scope, things should work as expected.
var piecesData;
//LOAD JSON
$.getJSON("users.js", function(data) {
piecesData = data;
numberOfPieces = data.users.length;
alert("Loaded "+numberOfPieces); // <------WORKS
});
//Select a piece
var pieceSelected = Math.floor(Math.random() * (numberOfPieces));
alert("pieceSelected: "+ piecesData.users[pieceSelected].Name);
Upvotes: 1