I'm trying to display two progress bars for multiple ajax requests. One progress bar reaches 100% each time one of my 18 ajax requests is complete and another reaches 100% when all 18 requests are complete. The first bar works great and is implemented in my ajax success callback. I'm having trouble triggering my second bar because it seems I need a second success callback...
Here is the code for my first ajax requests. It gets called 18 times because that is how many items are in my Config object.
for (var propt in Config) {
var db = '...';
var user = '...';
var pword = '...';
var func = '...';
var dat = {"...": propt };
var url = "https://...";
var callData = jQuery.extend({"Db": db, "User": user, "Password": pword, "Function": func}, dat);
$.ajax({
type: "POST",
url: url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(callData),
xhr: function() {
var xhr = new window.XMLHttpRequest();
//Download progress
xhr.addEventListener("progress", function(event){
var percentComplete = (event.loaded / event.total)*100;
//Do something with download progress
tableProgressBar(percentComplete);
}, false);
return xhr;
},
success: successHandlerRunTest1,
error: errorHandlerRunTest1,
dataType: "json"
});
$('#jsonMsg1').html('Running...');
$('#jsonRslt1').html(' ');
}
I would also like to fire this success function simultaneously.
success : function (serverResponse) {
response[response.length] = serverResponse;
$('#progress-bar').text(current + ' of ' + total + ' tables are done');
current++;
},
Unfortunately I don't believe I can call the second success function from within the first success function because the first receives special parameters containing JSON data.
I've tried something like...
success : function (serverResponse) {
response[response.length] = serverResponse;
$('#progress-bar').text(current + ' of ' + total + ' tables are done');
current++;
successHandlerRunTest1(data);
},
...but this doesn't work because the "data" object that my successHandlerRunTest1(data) receives is empty.
Is there a way to perform two success callbacks per ajax request?
Don't use the success
parameter.
Use the done
method to attach callbacks, as it returns the promise for chaining you can call it multiple times:
$.ajax({
type: "POST",
url: url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(callData),
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.addEventListener("progress", function(event){
var percentComplete = (event.loaded / event.total)*100;
tableProgressBar(percentComplete);
}, false);
return xhr;
},
dataType: "json"
})
.done(successHandlerRunTest1)
.fail(errorHandlerRunTest1)
.done(function (serverResponse) {
response[response.length] = serverResponse;
$('#progress-bar').text(current + ' of ' + total + ' tables are done');
current++;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With