user1768443
user1768443

Reputation: 1

Modify global javascript variable inside a function

I'm trying clone a json object inside a function wanting to access the object outside the function. But when function is done, the object still seems to be undefined. Seems like it's not the same variable?

var jsonUserObj;
$.getJSON("user.json", function(content){
    jsonUserObj = $.parseJSON(JSON.stringify(content));
    console.log(content);
    console.log(jsonUserObj); //looks fine!
});
console.log(jsonUserObj); //undefined

inside the callback function it contains all the data, but it does not remain outside of it. How to make it assessible globally?

Upvotes: 0

Views: 110

Answers (5)

jbabey
jbabey

Reputation: 46647

$.getJSON performs an ajax call, which is asynchronous. The code after it will continue evaluating while it waits for a response. When the response comes back, the program flow will jump back into the success/error/complete handlers of the ajax call.

tldr: Anything you do with data from an ajax call must be in the success handler of that ajax call.

Upvotes: 0

AGB
AGB

Reputation: 2448

Could it be a question of timing? If that getJSON method is firing asynchronously then it may not have returned it's value by the time you have fired the last line. Does that make sense?

Upvotes: 0

kabaros
kabaros

Reputation: 5173

$.getJSON is asynchronous so console.log at the end of your code runs before $.getJSON returns its result.

You should modify the variable inside the callback (where it looks fine) and then use the variable inside that function, this callback is the only place where you can guarantee your variable is set.

You could also use the synchronous version of $.ajax but that's really not recommended (and probably unnecessary).

Upvotes: 2

Miguel Sanchez Gonzalez
Miguel Sanchez Gonzalez

Reputation: 9713

You got a typo:

console.log(jsonUserObject);

It should be

console.log(jsonUserObj);

Upvotes: 1

Maess
Maess

Reputation: 4146

You need to declare var jsonUserObj outside a function.

Also it looks like you have a typeo, is it jsonUserObj or jsonUserObject?

Upvotes: 0

Related Questions