Skip to content

Instantly share code, notes, and snippets.

@niraj-shah
Created October 8, 2018 16:18
Show Gist options
  • Save niraj-shah/e508dd2d7db424fc7ecb6a652287efa1 to your computer and use it in GitHub Desktop.
Save niraj-shah/e508dd2d7db424fc7ecb6a652287efa1 to your computer and use it in GitHub Desktop.
Sequential Ajax Calls using jQuery
// parameters for ajax calls
var items = [
{ 'gender': 'male', 'nat': 'US' },
{ 'gender': 'female', 'nat': 'GB' }
];
// function to trigger the ajax call
var ajax_request = function(item) {
var deferred = $.Deferred();
$.ajax({
url: 'https://randomuser.me/api/',
dataType: "json",
type: 'GET',
data: item,
success: function(data) {
// do something here
console.log(data.results[0]);
// mark the ajax call as completed
deferred.resolve(data);
},
error: function(error) {
// mark the ajax call as failed
deferred.reject(error);
}
});
return deferred.promise();
};
var looper = $.Deferred().resolve();
// go through each item and call the ajax function
$.when.apply($, $.map(items, function(item, i) {
looper = looper.then(function() {
// trigger ajax call with item data
return ajax_request(item);
});
return looper;
})).then(function() {
// run this after all ajax calls have completed
console.log('Done!');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment