beNerd
beNerd

Reputation: 3374

Confusion in variable scope in javascript

I am having a function in js which populates a global array with values fetched as json from the server script:

function populateValues(id) {
    var values=new Array();

    $.getJSON(
        '<?PHP echo base_url();?>admin/forums/getForumById/' + id ,
        function(data){
            $.each(data,function(k,v){
                values.push(v);
            });
            alert(values[1]);
        }
    );
}

This works fine and alerts the desired value. But when i try to alert this after the loop, the values are lost and i get a undefined. Here is the case:

function populateValues(id) {
    var values=new Array();

    $.getJSON(
        '<?PHP echo base_url();?>admin/forums/getForumById/' + id ,
        function(data){
            $.each(data,function(k,v){
                values.push(v);
            });
        }
    );
    alert(values[1]);
}

Is it due to some closure construct forming? Or is it some fundamental concept i am lacking? Just curious to know why the values are not alerted even when i declared the array as global. Please shed some light.

Upvotes: 2

Views: 89

Answers (2)

Derek
Derek

Reputation: 4751

This will fix it, using the Promise object returned by the AJAX call:

function populateValues(id)
{
    var values=new Array();

    $.getJSON('<?PHP echo base_url();?>admin/forums/getForumById/'+id,function(data){
        $.each(data,function(k,v) {
            values.push(v);
        });
    }).done(function() { alert(values[1]); });
}    

Upvotes: 3

Justin Niessner
Justin Niessner

Reputation: 245399

The problem isn't scope.

The problem is that you're making an AJAX call and then immediately continuing to the next statement before the AJAX call completes.

Therefore, you alert(values[1]); before the array is filled from the AJAX call.

Upvotes: 15

Related Questions