I have the following Javascript function that should return an array of groups that are in database. It uses $.getJSON() method to call get_groups.php which actually reads from the database.
function get_groups() {
var groups = [];
$.getJSON('get_groups.php', function(response) {
for (var i in response) {
groups.push(response[i]);
}
}
return groups;
}
Unfortunately, this function does not work as expected because groups.push(response[i]); does not fill the
var groups = []; (as I understand it fills some other groups array, probably the global one).
Assuming that I don’t want to have a global groups variable, how would you solve this problem ?
It’s not a scope issue really, it’s the fact that
$.getJSON()is asynchronous, meaning that this part runs after you return:You need to call whatever function needs this data in the callback of the asynchronous request, so it runs when the data’s available, like this:
Currently you groups array is getting populated, just not when you need it to. If you absolutely have to return this (I strongly recommend using the asynchronous model the way it was intended) you can use the full
$.ajax()version and setasync:false. Again…don’t go that route if possible, stick to calling whatever function needs the data once it’s available, asasync: falsewill lock up the user’s browser.