Is there a proper way/design for doing this? or must I combine them into one function/event and base them off the values returned from the Ajax?
I have a dropdownlist with two Change Events/Functions like so,
$(document).ready(function () {
$("#ddlFacilityDatabases").change(UpdateCategoriesList).change(UpdateReportsList);
}
Both functions modify options on “#ddlCategories” and “#ddlReports”.
UpdateCategoriesList() modifies my “#ddlCategories” Options and UpdateReportsList() modifies my “#ddlReports” Options.
Here is one of my Functions (Only posting one since they’re nearly Identical, just changes a couple locations and names)
function UpdateCategoriesList() {
// Disable the Dropdown.
$("#ddlCategories").attr("disabled", true);
// Get Selection Value.
var Selection = {
"FacilityDatabaseName": $("#ddlFacilityDatabases").val()
};
// Send JSON to /Select/getCategories/.
$.ajax({
url: "/Select/getCategories/",
type: "GET",
dataType: "html",
data: Selection,
success: function (response, textStatus, jqXHR) {
// Parse Array.
var Categories = JSON.parse(response).categories;
// Clear Categories DropDownList.
$("#ddlCategories").children("option").each(function () {
if ($(this).val() != "") {
$(this).remove();
}
});
// Add New Categories.
var length = Categories.length;
for (var i = 0; i < length; i++) {
if (Categories[i] != null || Categories[i] != "") {
$("#ddlCategories").append("<option value=\"" + Categories[i] + "\">" + Categories[i] + "</option>");
}
}
},
complete: function () {
// re-enable dropdownlist
$("#ddlCategories").attr("disabled", false);
}
});
}
The Problem is when I add them both to the event handler like above it runs them but the page updates the dropdownlists after both the functions run. I need the first one to update the page then the second one to do so since the second is dependent on the first’s changes.
I think your problem is that you want to impose an ordering on asynchronous calls. If
UpdateReportsListmust come afterUpdateCategoriesList, then you have two options.Option 1: as Neal pointed out, call the second function from within the ajax call of the first.
Option 2: make both calls blocking, instead of asynchronous, like this:
then call
Overall, I think the first option is better, if you can change those two functions.