0

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!

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.