In order to use data from one loadJSON
call as parameters in a second call you will need to take into consideration that these are asynchronous calls. See Loading-external-files:-AJAX, -XML, -JSON
Instead of directly setting a variable to the return value you will unload the data in a call back function:
Callbacks
A callback is a function that is passed to another function as a parameter, and called by that other function. A callback function is useful when working with asynchronous functions because it allows us to specify some code to execute after the first asynchronous task has completed.
We've actually already used callbacks when we used setTimeout, setInterval, and addEventListener. For example, "doSomething" below is a callback function:
function doSomething() {
console.log("doing something!");
}
setTimeout(doSomething, 5000);
You will see callbacks used in p5.js and jQuery to tell the program what to do after the external data is received.
function setup() {
loadJSON("data.json", drawData);
}
loadJSON
loadJSON loads a JSON file and returns a JavaScript object. It takes two arguments, the path to the file, and the callback function. When the server has returned the JSON data and it has been parsed, drawData is run with the result automatically passed in as the variable "data".
function drawData(data) {
// person 1 bubble
fill(155, 30, 180, 180);
ellipse(250, 200, data.person1.age * 5, data.person1.age * 5); // person1.age = 30
fill(255);
text(data.person1.name, 210, 200); // person1.name = Morgan
// person 2 bubble
fill(180, 180, 34, 180);
ellipse(350, 200, data.person2.age * 5, data.person2.age * 5); // person2.age = 32
fill(255);
text(data.person2.name, 330, 200); // person2.name = Joss
}
For your purposes you will adapt code like this to chain your AJAX calls. In your case you will have a function that makes the second call and you will pass it to the first call to loadJSON
. The second call will also pass in a callback function which you will use to unload your final data.