52

I have to do something very simple, but there doesn't seem to be an easy way to do this, as far as I can tell. I just want to load JSON data from a remote source and store it in a global Javascript variable using jQuery. Here's what I have:

var my_json;
$.getJSON(my_url, function(json) {
  var my_json = json;
});

The my_json variable remains undefined. I think this is clearly a scope issue. It seems to me the $.getJSON method should return JSON, but it returns an XMLHttpRequest object. If I do this:

request = $.getJSON(my_url);
my_json = request.responseText.evalJSON();

That doesn't work because until the readystate == 4, the responsetext remains null. It seems you have to use the callback function to return the responsetext, since it fires on success.

It can't be this hard! Right?

Aaron
  • 732
  • 3
  • 8
  • 8

5 Answers5

130

This will do it:

var json = (function () {
    var json = null;
    $.ajax({
        'async': false,
        'global': false,
        'url': my_url,
        'dataType': "json",
        'success': function (data) {
            json = data;
        }
    });
    return json;
})(); 

The main issue being that $.getJSON will run asynchronously, thus your Javascript will progress past the expression which invokes it even before its success callback fires, so there are no guarantees that your variable will capture any data.

Note in particular the 'async': false option in the above ajax call. The manual says:

By default, all requests are sent asynchronous (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.

karim79
  • 339,989
  • 67
  • 413
  • 406
  • just to clarify for my benefit: $.getJSON is never a good option for synchronous style requests, even if i return data to my variable during the success callback? – user1026169 Apr 20 '13 at 20:54
  • +1 for related information but why are you making json variable null at the starting of the function. – Manoj Jun 13 '14 at 12:30
  • @Manoj There are 2 reasons [1] this block may be inside a method, and called multiple times. Therefore this would refresh the json variable. But if the ajax request will update this anyway what's the point? Well thats because ... [2] this is a coding convention incase the ajax request fails, then the user can test whether json is null. If it is, then it can be assumed the ajax request failed – Nick Mitchell Oct 21 '14 at 22:10
  • 8
    This is deprecated usage. `async: false` is no longer allowed. – CaptSaltyJack Oct 29 '14 at 21:23
  • This seems like a great solution but for some reason my json isn't outputting properly. I have a file formatted as "{[{id: 7, name: "Super Mario"},{id: 11, name: "Battletoads"}...]} but it it seems like the XML request is returning nothing. (Not a 404... just nothing). – itchyspacesuit Mar 02 '17 at 06:27
  • I know `async:false` is deprecated, but what if you need to only load the json data one time? If it is loaded asynchronously then it would load each time the data is needed, which means more requests. – bgmCoder Oct 26 '17 at 16:53
29

code bit should read:

var my_json;
$.getJSON(my_url, function(json) {
  my_json = json;
});
CountZero
  • 2,844
  • 4
  • 22
  • 20
0
<input  class="pull-right" id="currSpecID" name="currSpecID" value="">

   $.get("http://localhost:8080/HIS_API/rest/MriSpecimen/getMaxSpecimenID", function(data, status){
       alert("Data: " + data + "\nStatus: " + status);
    $("#currSpecID").val(data);
    });

enter image description here enter image description here

MAFAIZ
  • 681
  • 6
  • 13
0

var itens = null;
$.getJSON("yourfile.json", function(data) {
  itens = data;
  itens.forEach(function(item) {
    console.log(item);
  });
});
console.log(itens);
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
</head>
<body>
</body>
</html>
  • 4
    Welcome to stack overflow :-) Code-only answers aren't useful for community. Please explain why your code solves the problem. See [answer] – JimHawkins Jul 13 '17 at 10:48
0
  • this will get JSON file externally to your javascript variable.
  • now this sample_data will contain the values of JSON file.

var sample_data = '';
$.getJSON("sample.json", function (data) {
    sample_data = data;
    $.each(data, function (key, value) {
        console.log(sample_data);
    });
});
Nick ODell
  • 15,465
  • 3
  • 32
  • 66