Reputation: 744
On page load I need to call an API. When all AJAX call are finished (completed) I want do unlock UI. The problem is that I don't know how many times i will call API. It might be once or 10.
My code:
$(document).ready(function () {
callAPI(yourApiKey);
});
and functions:
function getRates(yourAPIKey, contractCode, startDate, endDate) {
// I did cut some code here
$.ajax({
url: ratesEnquiry,
type: 'GET',
dataType: "jsonp",
jsonp: "callback",
complete: function (response, responseCode) {
},
success: function (json) {
$.each(json, function (index, value) {
populateValues("rate", this.ContractCode, this.RoomTypeCode, this.Date.substr(0, 10), this.RoomPrice);
populateValues("hrate", this.ContractCode, this.RoomTypeCode, this.Date.substr(0, 10), this.RoomPrice);
});
}
});
}
function getAvailability(yourAPIKey, contractCode, startDate, endDate) {
// I've cut off some code here as well
$.ajax({
url: availabilityEnquiry,
type: 'GET',
dataType: "jsonp",
jsonp: "callback",
//jsonpCallback: "jsonpCallback",
complete: function (json, responseCode) {
//console.log(response); console.log(responseCode);
//alert("complete");
},
success: function (json) {
$.each(json, function (index, value) {
populateValues("avail", this.ContractCode, this.RoomTypeCode, this.Date.substr(0, 10), this.Quantity);
populateValues("havail", this.ContractCode, this.RoomTypeCode, this.Date.substr(0, 10), this.Quantity);
// alert(this.RoomPrice);
});
}
});
}
function callAPI(yourAPIKey) {
// I've cut off some code here
$.blockUI({ message: '<span class="loader green" original-title="1Loading, please wait…"></span><h3> Please wait...</h3>' });
$.ajax({
url: enquiry,
type: 'GET',
dataType: "jsonp",
jsonp: "callback",
complete: function (response, responseCode) {
},
success: function (json) {
$.each(json.Contracts, function (index, contract) {
ContractsArray[Count] = contract.ContractCode;
Count++;
});
for(var i = 0; i < Count; i++){
getAvailability(yourAPIKey, ContractsArray[i], startDate, endDate);
getRates(yourAPIKey, ContractsArray[i], startDate, endDate);
}
}
});
}
Can I use ajaxStop or ajaxComplete do sovle that?
Upvotes: 3
Views: 6516
Reputation: 620
use counter and check if that for every call add 1 to that counter and for every finish minus 1 to that counter, and if counter will be 0, you know all api calls are finished simple example:
var calls = 0;
function makeCall(url) {
calls++;
$.ajax({
complete: function(resp) {
calls--;
}
});
}
Upvotes: 5
Reputation: 3758
.ajaxComplete should work It registers a handler for when ajax requests are completed. Essentially, this handler is called whenever an ajax request completes.
Why would you think it doesn't work?
http://api.jquery.com/ajaxComplete/
Upvotes: 0