Instantly share code, notes, and snippets.

Embed
What would you like to do?
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