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.
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]); });
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With