My scenario is this:
When the page is loaded, a listbox with countries is loaded.
By selecting an item from a dropw down list, a country item in the listbox is selected using jQuery.
Now that a country is selected in the listbox, I call a function which retrieves cities and populate a city listbox.
The code looks something like this:
$('#MyDropDownList').change(function() {
(...) // Selected country is set here
populateCityListBox();
//this alert is undefined. Probably because it's triggered before the callback in populateCityListBox()
alert(jQuery('#cityListBox option[value=Oslo]').val());
});
function populateCityListBox()
{
//Get ID for selected country
var ctryID = jQuery("select#countryListBox").val();
jQuery.post("wp-content/themes/storelocator/include/jquery_bll.php", { instance: 'getCitiesByCountry', countryID: ctryID },
function(data)
{
var options = '';
for (var i = 0; i < data.length; i++) {
options += '<option value="' + data[i].city + '">' + data[i].city + '</option>';
}
jQuery("select#cityListBox").html(options);
// This alerts the option text, which also is Oslo
alert(jQuery('#cityListBox option[value=Oslo]').val());
}, "json");
}
My problem is this: I’m not able to retrieve values in the city listbox after I have run the function populateCityListBox();. I am able to retrieve values in the $.post callback.
What can I do to be able to retrieve the values after the function is triggered? (I know it has to do something with some stuff being callback, while others run “realtime”… or something like that).
You are correct. Since your request is asynchronous, the code keeps on running. You could potentially substitute something like so:
By placing
callbackas an argument ofpopulateCityListBox, we are able to call that function inside of yourchangeup there. In essence, it is just a ‘modified’ callback of sorts: we are just executing yet another function in the callback. This lets you run the functionpopulateCityListBoxindependently in a console like you could and still be able to use the application logic or whatnot.Hope this helps.