Progress Bar For Multiple Ajax Requests With Stages Of Completion. Is It Possible?
Solution 1:
Well the way i had created such a progress bar was, since you want each of your function to be called one after another, that is completion of one should trigger the other, XMLHttpRequest has onreadystate change event. you can use that event to confirm that the first request got executed successfully or not, and then trigger the second one, at each change you will have progress bar incremented by whatever % you want to.
functionpostdata()
{
var xhr = newXMLHttpRequest();
xhr.open
(
"POST",
Url,
true
);
xhr.send();
xhr.onreadystatechange = function()
{
if (xhr.readyState == 4)
{
//Call next function here and increment progressbar
}
}
}
hope this helps
Solution 2:
Yes, it is possible. You can create an array containing each ajax call. Set <progress>
element max
attribute to 100/array.length
. Divide evt.loaded / evt.total
of individual progress
event by array .length
to set value
of <progress>
element. You could also use Promise.all()
, .then()
to process array of functions returning a Promise
from ajax call and update <progress>
element.
html
<label></label><progressvalue="0"min="0"max="100"></progress>
javascript
var progress = document.querySelector("progress");
var url = "/echo/html/";
functionrequest(url) {
var len = arr.length;
returnnewPromise(function(resolve, reject) {
var xhr = newXMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = ((evt.loaded / evt.total) * (progress.max / len))
/ len;
progress.value += percentComplete;
console.log(progress.value, percentComplete);
if (evt.total === evt.loaded) {
requests += 1;
}
if (progress.value == progress.max && requests === len) {
progress.previousElementSibling.innerHTML = "upload complete";
// you could call `resolve()` here if only interested in// `upload` portion of requestalert("upload complete");
}
}
}, false);
xhr.onload = function() {
resolve(this.responseText)
};
xhr.onerror = reject;
xhr.open("POST", url, true)
xhr.send("html=" + Array(100000).fill(1).join(""));
})
}
var arr = [], requests = 0;
arr.push(request, request, request);
Promise.all(arr.map(function(req) {
returnreq(url)
}))
.then(function(data) {
console.log(data);
})
.catch(function(err) {
console.log(err)
})
jsfiddle https://jsfiddle.net/v2msL7hj/3/
Post a Comment for "Progress Bar For Multiple Ajax Requests With Stages Of Completion. Is It Possible?"