JSON is asynchronous meaning the data traffic goes both ways, so when you try to take data from one function to another functions you need to do a callback function which can be tricky. However, I would look into using fetch (or $.get in JQuery I believe) or looking into callback functions which once you get the hang of is really not that hard.
here’s a small example of some code in what I did for a vanilla JavaScript game that I have develop
/* retrieve User Data from hs_table */
const retrieveHSTableUISuccess = function (info) {
displayHSTable(info);
};
/* If Database Table fails to save data in mysql table */
const retrieveHSTableUIError = function (error) {
console.log("Database Table did not load", error);
};
/* Create High Score Data using fetch */
const createHSTable = (retrieveUrl, succeed, fail) => {
var max = 5; // Maximum Records to Be Displayed
var maxium = {};
maxium.max_limit = max;
fetch(retrieveUrl, {
method: 'POST', // or 'PUT'
body: JSON.stringify(maxium)
})
.then((response) => handleErrors(response))
.then((data) => succeed(data))
.catch((error) => fail(error));
};
at the very top is the call to the displayHSTable(info) and that is the most import thing to remember as the data (info in this case) never leaves a function (callback function). Now I like using fetch ($.get) as I don’t have to worry about parsing the JSON data as it is already parsed. However, doing it the other way with straight AJAX call isn’t that much harder, but forgetting to parse the data coming in can be a pain as you think it’s a problem with the way you are bring back the data. Anyways, it’s frustrating and it took me a long time to understand it, but what I finally did was watched some tutorials online.
I hope that helps ~ John
Oh, I forgot mention you might have to have an API key if you are bringing in data from a third party. That can also trip you up.