0

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?

  • `I managed to make it work by doing all the operations inside the getJSON function` This is the correct way of doing it. `But the function is called inside a forEach loop` If you mean that you're sending AJAX requests in a loop, that's not a good idea. Collate all information in to a single request and send it. Then dissect the response as required. – Rory McCrossan May 10 '18 at 13:29
  • @RoryMcCrossan thanks for the link, it's very insightful. Yes, that's what I mean. Because part of the url is the values in the array. I'm not sure that I can get all the information in one call. – Monika Diao May 10 '18 at 13:45

0 Answers0