0

I cannot assign the data parameter of the jQuery.getJSON function to variable.

var storage;

$.getJSON('server.json', function(data) {
    storage = data;
});

console.log(storage);

EDIT : ok I understand, so let's say the 'storage' variable is equals the server.json file, but i can't use it because the lines of code below the $.getJSON executed before the server answered, so how can i check whenever the server is answered?

2
  • Think about this piece of code for a while. Why would $.getJSON have the additional complexity of using a callback if it ran synchronously...? Commented Jan 2, 2013 at 12:57
  • @MattiVirkkunen but how can i still assign the JSON file to variable?? Commented Jan 2, 2013 at 12:59

1 Answer 1

3

By "after that", you mean "below in the code", I suppose.

If so, then it's not after the server answered.

Use this :

var storage;
$.getJSON('server.json', function(data) {
    storage = data;
    console.log(storage);
});

The callback you give to getJSON is called after the server has (asynchronously) answered. That's where you must handle the result. The lines of code just below $.getJSON(...); are executed before the server answered so they can't use the result.

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

4 Comments

@Israel: You can't do that. That's not how the event/callback driven model JS is based on works.
@IsraelG. You must understand what it means for a query to be asynchronous. A javascript application is event-driven (events being the response of a server or a user interaction). You must understand this point. You can't simply have a synchronous code.
@dystroy ok I understand, so let's say the 'storage' variable is equals the server.json file, but i can't use it because the lines of code below the $.getJSON executed before the server answered, so how can i check whenever the server is answered?
@IsraelG. You can call your method in the $.getJSON() where the data is defined. Then your method will have access to the right data when it arrives. Thats asynchronous callback style

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.