0

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;
    }
});
123
  • 127
  • 3
  • 18
  • Have you tried this: https://stackoverflow.com/questions/15494781/js-progressevent-is-only-fired-when-finished ? – saulotoledo Jul 28 '19 at 16:11
  • @saulotoledo Yeah I tried, it didn't do nothing... same problem... – 123 Jul 28 '19 at 16:45
  • Could you create a running example at https://codepen.io/pen ? You could use files from https://sample-videos.com/ while building the example. – saulotoledo Jul 28 '19 at 16:47
  • @saulotoledo I'm not uploading / downloading any sort of media... I'm just sending a regular POST request using AJAX, and in my backend there's a delay of 15 - 50 seconds until there's a response to the request, because the data that's being returned is fetched off of multiple outside APIs... – 123 Jul 28 '19 at 17:49
  • my problem was that in both functions I made the same callback request "xhr.upload.addEventListener" instead of having one of them be "xhr.addEventListener", so both of the callbacks were showing the same upload response instead of one showing for the upload and another one for the download... now it's working as I expected it to.. (it shows the 50% of the upload and waits for few seconds while the backend fetches the data off of the APIs and then it shows the remaining 50% of the download...) – 123 Jul 28 '19 at 21:01

0 Answers0