With a deferred object
you could chain all your ajax calls returning a promise inside some chained pipe()
methods (see the console output below)
Markup and js
<body>
<input type="checkbox" checked />
<input type="checkbox" checked />
<input type="checkbox" checked />
<input type="checkbox" checked />
</body>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
function doRequest() {
return $.post("script.php").done(function(response) {
console.log('Loaded in %d seconds', response);
});
}
$(document).ready(function(){
var dfd = $.Deferred(),
chain = dfd;
$('input:checked').each(function() {
chain = chain.pipe(function() {
return doRequest().promise();
});
});
chain.done(function() {
console.log('done')
});
return dfd.resolve();
});
</script>
script.php
<?php
$seconds = rand(2, 5);
sleep($seconds);
header("Content-type: text/html");
echo($seconds);
?>
Sleep()
was used only to emulate a random latency on the response. On the javascript console you should see something like this:
