I have succeeded in getting all of the necessary components working to trigger updates in cascading dropdowns with the following code when I have alert messages firing.
However, when I comment out the alerts it appears that things move too quickly. Is there a way to ensure that my source dropdown has completed its update prior to firing the change on my destination dropdown?
$(document).ready(function() {
//Default bu (company) listing
$.post("select_bu.php", {
id: 1
}, function(data) {
$("select#id_buid").html(data);
});
//Default division listing
$.post("select_division.php", {
id: 1
}, function(data) {
$("select#id_divid").html(data);
});
//Default department listing
$.post("select_dept.php", {
divid: 11
}, function(data) {
$("select#id_deptid").html(data);
});
//Default title listing
$.post("select_title.php", {
deptid: 12
}, function(data) {
$("select#id_titleid").html(data);
});
//Default location listing
$.post("select_loc.php", {
id: 1
}, function(data) {
$("select#id_locid").html(data);
});
//Change to Business Unit triggers updated division listing and location
$("select#id_buid").change(function() { * //alert("Change of BU triggering change in Division and Location.");*
var id = $("select#id_buid option:selected").attr('value');
$.post("select_division.php", {
id: id
}, function(data) {
$("select#id_divid").html(data);
});
$.post("select_loc.php", {
id: id
}, function(data) {
$("select#id_locid").html(data);
});
$("#id_divid").trigger("change");
});
//Change to Division triggers updated department listing
$("select#id_divid").change(function() {
//alert("Change of Division triggering change in Department.");
var id = $("select#id_divid option:selected").attr('value');
$.post("select_dept.php", {
divid: id
}, function(data) {
$("select#id_deptid").html(data);
});
$("#id_deptid").trigger("change");
});
//Change to Department triggers updated title listing
$("select#id_deptid").change(function() {
//alert("Change of Department triggering change in Title.");
var id = $("select#id_deptid option:selected").attr('value');
$.post("select_title.php", {
deptid: id
}, function(data) {
$("select#id_titleid").html(data);
});
});
});
You should move triggering to the success function of
$.post. Ajax call is done asynchronously, which means that after creating the request script moves to the next command and ajax request is handled in the background. If you want them to appear one after another you have to call the next in the response handler of the previous. So it can look like that: