Demonstration of sequencing multiple ajax calls using $.when

by Darth Vader

HTML

<script src="https://jquery-json.googlecode.com/files/jquery.json-2.2.js"></script>
<!-- All output is part of the console -->

JavaScript

var filters = ["zone", "region", "county"];
var options = {
    zone: ["East", "West", "North", "South"],
    region: ["New York", "Rhode Island", "New Jersey", "Delaware"],
    county: ["Somerset", "Bergen", "Morristown", "Mercer"]
}

    function getFilterData(filter) {
        var actualDelay = 1 + parseInt(Math.floor(Math.random() * 15), 10);
        console.log("In Filter Data for Filter", filter, "Setting up delay as", actualDelay);
        return $.ajax({
            url: "/echo/json/",
            type: "POST",
            data: {
                json: $.toJSON({data: options[filter]}),
                delay: actualDelay
            }
        }).done(function(data) {
              console.log("Completed the call for ", filter, " with data obtained as", data);  
        });
    }

$(document).ready(function () {
    var selections = [];
    function start() {
        for (var index = 0; index < filters.length; index++) {
            selections[index] = getFilterData(filters[index]);
        }
        
        $.when.apply($, selections).done(function() {
             console.log("Done with all the selections");   
        });
    }
    start();
});