0

I'm having a bit of trouble using data loaded from a JSON file immediately after I load it. Code below.

newdata = []

$.getJSON(file, function(data) {
            $.each(data.items, function(i,item){
            if (item.id != undefined) {
                if (item.id === cl) {
                    newdata.push(item.id);
                }
            }
            });
        });

console.log(newdata);

The console.log statement doesn't return the data though, it returns an empty array []. However, if I call the variable data in my chrome debugger, it returns the correct array. How do I use data with the correct elements immediately after I create it from the JSON file?

2
  • getJSON returns data to the callback function in asynchronous fashion. So, console.log is executed before the data is returned. Commented Oct 15, 2013 at 20:12
  • Your console.log is firing before your request is complete. The data is available inside the callback exactly as you'd expect. There are something like 200 questions on this exact topic on SO. Commented Oct 15, 2013 at 20:12

3 Answers 3

1

Should be written like this,

newdata = []

$.getJSON(file, function(data) {
            $.each(data.items, function(i,item){
            if (item.id != undefined) {
                if (item.id === cl) {
                    newdata.push(item.id);
                }
            }
            });
              console.log(newdata);
        });
Sign up to request clarification or add additional context in comments.

3 Comments

Made a naming error, the first data = [] should be newdata = []. So logging data would be different from logging newdata. Is there any way to get around the async problem then?
Updated it to newdata. The async behaviour is how ajax works so you will have to apply your logic within the callback.
@q2liu The "A" in AJAX stands for "Asynchronous". And you really don't want to be synchronous (just think about what that would mean).
0

jQuery.getJSON is asynchronous. You should read the documentation on it to become familiar with how its success callback works.

The function that receives the JSON data is called on success, but the actual $.getJSON function returns immediately and execution continues. So, in practice, this means that your console.log(data) gets executed before the JSON data comes back, but by the time you log it manually in the Chrome console, the data has been retrieved.

The jQuery AJAX methods also return objects that implement a promise-like API, so you can use that, too.

There are many, many questions about this topic on both Stack Overflow and other resources.

The following code uses both the success function argument and the Deferred object methods. You can do whatever you want with your data in the handleData function.

function handleData(data) {
    // you can do whatever you want with your data here
    console.log(data);
}

function formatData(data) {
    var formatted = [];
    $.each(data.items, function(i,item){
        if (item.id != undefined) {
            if (item.id === cl) {
                formatted.push(item.id);
            }
        }
    });
    return formatted;
}

$.getJSON(file, formatData).done(handleData);

Comments

0

Another method is:

$.ajaxSetup({
    async: false
});

But after being pointed out that the method is deprecated and the better way to do this is given by melc and Thomas Upton.

2 Comments

The official documentation strongly recommends against the use of jQuery.ajaxSetup. You can probably set that option on that individual $.getJSON call, but why would you want it to be synchronous?
Also, see here that as of jQuery 1.8, the use of async: false is deprecated in favor of the Deferred methods.

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.