Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XHR progress event not firing until upload completes?

I'm using the following $.ajax command to upload a file from a PhoneGap application:

function updateProgress( evt ) {
    if ( evt.lengthComputable ) {
        var percentComplete = evt.loaded / evt.total * 100;
        console.log( percentComplete + "%" );
    }
}

$.ajax({
    url: url,
    type: "POST",
    data: data,
    cache: false,
    dataType: "json",
    processData: false, 
    contentType: false, 
    success: successCallback,
    error: errorCallback,
    xhr: function() {
        var xhr = new window.XMLHttpRequest();
        xhr.addEventListener( "progress", updateProgress, false);
        return xhr;
    }
});

The upload works fine. However the progress event only fires one time, once the upload has completed. It does not actually fire during uploading - so upload progress does not actually display. There is just a pause while it is uploading, and then it displays 100%.

Any ideas what I am doing wrong?

like image 593
user1031947 Avatar asked Oct 31 '14 17:10

user1031947


1 Answers

The upload progress events are fired on xhr.upload, so attach the listener to that rather than xhr. There are also progress events on the xhr object but this is for the response coming back from the server.

See the MDN article for more details.

xhr.upload.addEventListener('progress', updateProgress, false)

(Thanks to A. Wolff and his comment on the OP.)

like image 183
tremby Avatar answered Oct 13 '22 20:10

tremby