2

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.

3
  • 4
    The problem isn't scope, it's asynchronicity. Commented Dec 28, 2012 at 15:38
  • But when i try to alert this after the loop Your alert is outside the loop in both examples. The only difference is that example 1 is inside the get and example 2 is outside it, hence the asynchronicity issue. Commented Dec 28, 2012 at 15:45
  • @FrançoisWahl Correct! Sorry by loop i meant the ajax construct. Commented Dec 28, 2012 at 15:48

2 Answers 2

15

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.

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

1 Comment

so its something due to non-blocking nature of js :) Thanks a ton. Perfect answer.
3

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]); });
}    

1 Comment

Would the alert not always work just fine immediately after the each function? Like in ops first example

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.