views:

24

answers:

1

I might be wrong about what is actually happening here but i have 3 Html.dropdownlists. And im using jquery to handle filtering which does actually work. However, there is some odd behaviour which i think might be because data isnt finished loading before the next function is called.

For instance:

Some background. Company: Owns several field offices Field Office: Owns several facilties So logically, when you change company, field offices should change, which then changes facilities.

$(function () {
        $(document).ready(function () {
            var cid = $("#CompanyId").val();
            $.post("/ManifestSearch/GetFilteredFieldOffices", { id: cid }, function (data) {
                $("#FieldOfficeId").loadSelect(data);
            });
            var fid = $("#FieldOfficeId").val();
            $.post("/ManifestSearch/GetFilteredFacilities", { id: fid }, function (data) {
                $("#FacilityId").loadSelect(data);
            });
        });
    });

Now, when the page loads, everything looks fine. All the dropdownlists have the correct data.

When i change company, this calls.

$(function () {
        $('#CompanyId').change(function () {
            var cid = $(this).val();
            $.post("/ManifestSearch/GetFilteredFieldOffices", { id: cid }, function (data) {
                $("#FieldOfficeId").loadSelect(data);
            });
            var fid = $("#FieldOfficeId").val();
            $.post("/ManifestSearch/GetFilteredFacilities", { id: fid }, function (data) {
                $("#FacilityId").loadSelect(data);
            });
        });
    });

This changes the field offices to the correct list, however facilities changes to whatever field offices was set to before the company change occured. I dont know enough about jquery to figure out exactly what is going on, but my instinct tells me that the two posts are happening at the same time, and the second post happens before the first one is finished.

+2  A: 

It's the nature of an asynchronous request.. you don't know which order they will finish in so you can't always assume the data from the first one will be available to the second one.

Ideally, your second request should be within the onSuccess callback function of the first request, with an onFailure/onError function handler to take care of any problems that arise.

Jason
I saw somewhere that you can set async to false. Is that true?
John Stuart
Got it. I put the second controller call inside the success of the first one. Thanks!
John Stuart
Also note - there are jQuery plugins that queue ajax requests to be received in order. I've personally used and enjoyed http://www.protofunc.com/scripts/jquery/ajaxManager/
JonoRR
You can set async to false, and that would be another way of doing it. I don't generally do it that way, myself.
Jason