0

This ain't working:

   $(document).ready(function () {
    var getJ = null;
    var url = 'JSON file URL here';
    $.getJSON(url, function (data) {
         getJ = [...data]
    });
   }); 
   document.write(getJ[0].Tag)

(The tag here contains some data from JSON file)

This only works when I output getJ inside the function; however, I want it outside.

Zuberi
  • 35
  • 6
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – ASDFGerte Dec 08 '19 at 22:51

1 Answers1

1

A few things are in play here:

  1. Your $(document).ready function is a callback which is executed whenever the document is fully loaded. Your document.write call does not have a callback so it is most certainly going to be executed before anything you're doing in .ready, and getJ has not yet been assigned.

  2. Your $.getJSON call is also accepting a callback function which means it waits for the request to be executed before it can set the result. Those functions are all delayed whereas document.write is not. You can either make the GET request synchronous (set async to false). You can do that by using the full $.ajax call: https://stackoverflow.com/a/2765848 OR you can just start chaining your functions together as synchronous calls are deprecated and may not be supported for very long. Here is an example of how you would do this with jQuery: https://stackoverflow.com/a/16045729

  3. Although var in JS will make the variable accessible in a global scope, please don't confuse yourself or others later by declaring it in a scope that you don't even plan to use it in. You want to access this variable outside of your $(document).ready call so you should declare it before that function to make it clear that you expect it to be changed.

djsoteric
  • 188
  • 1
  • 10