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?

5 Answers 5

132

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.

Sign up to request clarification or add additional context in comments.

6 Comments

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?
+1 for related information but why are you making json variable null at the starting of the function.
@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
This is deprecated usage. async: false is no longer allowed.
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).
|
29

code bit should read:

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

5 Comments

how does this avoid the asynchronous issue mentioned above?
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.
It simply doesn't prevent the asynchronous issue.
I am getting a CORS error when tying this on Chrome. Why does loading a local file invoke CORS?
@jDub9 because you're loading from file:/// and not from http(s)://
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

Comments

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>

1 Comment

Welcome to stack overflow :-) Code-only answers aren't useful for community. Please explain why your code solves the problem. See How to Answer
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);
    });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.