load json into variable
Asked Answered
K

5

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?

Kwangju answered 1/2, 2010 at 15:2 Comment(0)
G
131

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.

Gardant answered 1/2, 2010 at 15:8 Comment(6)
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?Bypath
+1 for related information but why are you making json variable null at the starting of the function.Bardo
@Bardo 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 failedElectron
This is deprecated usage. async: false is no longer allowed.Dozier
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).Sociability
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.Forbear
E
29

code bit should read:

var my_json;
$.getJSON(my_url, function(json) {
  my_json = json;
});
Egide answered 1/2, 2010 at 15:7 Comment(5)
how does this avoid the asynchronous issue mentioned above?Bypath
Most probably trying to force synchronous ajax call is a bad idea, ajax was meant for asynchronous calls. This answer should be a desired solution for a problem described in question, +1 from me.Newness
It simply doesn't prevent the asynchronous issue.Kenwood
I am getting a CORS error when tying this on Chrome. Why does loading a local file invoke CORS?Stratosphere
@jDub9 because you're loading from file:/// and not from http(s)://Oxalis
C
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

Chuppah answered 16/8, 2015 at 10:48 Comment(0)
H
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>
Hazzard answered 13/7, 2017 at 1:43 Comment(1)
Welcome to stack overflow :-) Code-only answers aren't useful for community. Please explain why your code solves the problem. See How to AnswerBaumbaugh
K
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);
    });
});
Kutch answered 10/12, 2018 at 5:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.