jett
jett

Reputation: 1276

jquery variable scope within function

meclass.prototype.switch = function() {
var items = [];
$.getJSON('http://localhost/jsoner.php', function(data) {
    $.each(data, function(key, val) { 
        items.push(val);
        alert(items[0]); //this works

    });
});
alert(items[0]); //this does not
}

I have been tinkering with this for awhile and not really getting it. I am having this problem in all of my jquery functions so it is something basic that I just haven't learnt- and haven't had luck finding answers on.

Upvotes: 2

Views: 257

Answers (1)

James Allardice
James Allardice

Reputation: 165951

The getJSON method is asynchronous. Execution will continue with the following statement straight away. The callback function will be executed some time later, whenever the server has responded to the request.

For that reason, any code that relies upon the result of the async request will need to be moved inside the callback function.

This is effectively what happens:

var items = []; //Declare `items`, empty array
//Make AJAX request
alert(items[0]); //It's still an empty array
//Wait some arbitrary amount of time...

//AJAX request complete, run the callback function
alert(items[0]); //Inside callback, items now contains elements

Upvotes: 6

Related Questions