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.
But when i try to alert this after the loopYour alert is outside the loop in both examples. The only difference is that example 1 is inside thegetand example 2 is outside it, hence the asynchronicity issue.