XMLHttpRequest Level 2 - Determinate if upload finished XMLHttpRequest Level 2 - Determinate if upload finished ajax ajax

XMLHttpRequest Level 2 - Determinate if upload finished


The event you want to listen to is readystatechange on the XHR object (not on XHR.upload). readyState is 4 when the upload has finished sending and the server closes the connection. loadend/load fire when the upload has finished regardless of whether the server closes the connection. Just for reference, here are the events you can listen to and when they fire:

    var xhr = new XMLHttpRequest();    // ...    // do stuff with xhr    // ...    xhr.upload.addEventListener('loadstart', function(e) {      // When the request starts.    });    xhr.upload.addEventListener('progress', function(e) {      // While sending and loading data.    });    xhr.upload.addEventListener('load', function(e) {      // When the request has *successfully* completed.      // Even if the server hasn't responded that it finished.    });    xhr.upload.addEventListener('loadend', function(e) {      // When the request has completed (either in success or failure).      // Just like 'load', even if the server hasn't       // responded that it finished processing the request.    });    xhr.upload.addEventListener('error', function(e) {      // When the request has failed.    });    xhr.upload.addEventListener('abort', function(e) {      // When the request has been aborted.       // For instance, by invoking the abort() method.    });    xhr.upload.addEventListener('timeout', function(e) {      // When the author specified timeout has passed       // before the request could complete.    });    // notice that the event handler is on xhr and not xhr.upload    xhr.addEventListener('readystatechange', function(e) {      if( this.readyState === 4 ) {        // the transfer has completed and the server closed the connection.      }    });


Based on https://bugzilla.mozilla.org/show_bug.cgi?id=637002.

Let's go for a complete working example...

// YOUR (SIMPLE) JAVASCRIPT FILEvar form = new FormData(), xhr = new XMLHttpRequest();form.append('inputname', YOURFILE);xhr.open('POST', 'http://oneserver/onephpfile', true);xhr.setRequestHeader('X-CSRF-Token', 'somestring');xhr.onreadystatechange = function () {    if ((xhr.readyState === 4) && (xhr.status === 200))        // do other thing with xhr.responseText.trim()};xhr.upload.addEventListener('loadstart', showProgressBarFunction, false);xhr.upload.addEventListener('progress',  updateProgressBarFunction, false);xhr.upload.addEventListener('load',      updateProgressBarFunction, false);xhr.send(form);// YOUR FIRST (SIMPLE) PHP FILEheader('Content-Type: text/plain; charset=utf-8');header('Cache-Control: no-cache, must-revalidate');sleep(20);echo 'file processing ended';

With this first PHP file, you will see: 10%... 50%... 75%... 'do other thing' with Firefox (4/10/28/32) and IE (10/11). However you we will see: 10%... 50%... 75%... 100%... 'do other thing' with Chrome/Chromium (33/37) and Opera (24).

// YOUR SECOND (SIMPLE) PHP FILEheader('Content-Encoding: chunked', true);header('Content-Type: text/plain; charset=utf-8');header('Cache-Control: no-cache, must-revalidate');ini_set('output_buffering', false);ini_set('implicit_flush', true);ob_implicit_flush(true);for ($i = 0; $i < ob_get_level(); $i++)    ob_end_clean();echo ' ';sleep(20);echo 'file processing ended';

With this second PHP file, you will see: 10%... 50%... 75%... 100%... 'do other thing' with Chrome/Chromium (33/37/53), Opera (24/42), Firefox (4/10/28/32/45), IE (10/11) and Edge (14)!


This is a relatively known downfall of the hTML5 spec, when they could have easily extended it to add information such as timeRemaining and transferSpeed.

Have you considered using math.round instead of math.ceil for var percent so that you are baking in a bit of fuzziness that would help get around a few % points being off?

You should also add another listener for loadComplete, if you are getting the UI stuck at <100% even though it is complete on the backend:

//only fires oncexhr.addEventListener('loadend', uploadComplete, false);function uploadComplete(event) {    console.log('rejoice...for I have completed');    //do stuff}