It seems to be the same issue posted in these threads jQuery getJSON save result into variable and Variables set during $.getJSON function only accessible within function. However, it didn't work after applying the solutions to them.
That is,
var a = "";
$.getJSON(url, callbackFuncWithData);
function callbackFuncWithData(data) {
a = "something";
}
console.log(a); // the output is ""
and
var a = "";
$.ajax({
Type: "GET",
url: url,
async: false,
dataType: "json",
success: function(data) {
a = "something";
}
});
console.log(a); // output ""
It's a chanllenge from FreeCodeCamp, here is my pen if you wish to view the code https://codepen.io/MonikaDiao/pen/xjYwJV. I managed to make it work by doing all the operations inside the getJSON
function. But the function is called inside a forEach
loop. It would be better to set the final html
outside the loop. I simply could figure out why it doesn't work as expected. Does the loop also introduce synchronous problem?