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.
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.