I'm trying to add percentage to my AJAX call and I'm overriding the xhr and adding the listeners (for upload and for download) but they always get called once and also they get called right when I call the AJAX (and the "complete" callback gets called few seconds after them, and it shouldn't be like that, the download listener should get to 100% only when the complete is called)
I'm not uploading nor downloading huge amounts of data in this AJAX call, it just that the backend takes few seconds to fetch all the needed data off of several APIs and I want to let the user know that there's a task in progress and that the webpage didn't get stuck/timeout...
Here's my code:
$.ajax({
...
...
...
complete: function(){
console.log("complete");
},
xhr: function(){
var xhr = new window.XMLHttpRequest();
//Upload progress
xhr.upload.addEventListener("progress", function(evt){
var percentComplete = evt.loaded / evt.total;
console.log(Math.round((percentComplete * 100) / 2) + "%");
}, false);
//Download progress
xhr.upload.addEventListener("progress", function(evt){
var percentComplete = evt.loaded / evt.total;
console.log(Math.round((percentComplete * 100) / 2) + "%");
}, false);
return xhr;
}
});