0

Here is the deal: I am trying to read a file in JS and to affect its content to a variable I can manipulate outside the parsing function. In other words:

var content = "";
$.getJSON(dataPath, function(obj) {
    content = obj;
    console.log(content) //first log
 });
 console.log(content) // second log

I don't understand why the first log show the right content (JSon from a file), whereas the second says content is undefined.

What am I missing ?

  • 1
    `What am I missing?` understanding of promises and how they work. https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call – nbokmans Mar 28 '22 at 13:09
  • That is exactly what I am looking for. Thanks for the pointer (can't fix the problem yet, but a least I know where to search !) – Edouard Batot Mar 28 '22 at 13:19
  • A very quick fix: https://stackoverflow.com/questions/2177548/load-json-into-variable Which post stands: var jsonContent = (function () { var json = null; $.ajax({ 'async': false, // Synchronize ! 'global': false, 'url': dataPath, 'dataType': "json", 'success': function (data) { json = data; } }); return json; })(); – Edouard Batot Mar 28 '22 at 13:51

0 Answers0