Can onprogress functionality be added to jQuery.ajax() by using xhrFields?

Short answer:
No, you can’t do what you want using xhrFields.

Long answer:

There are two progress events in a XmlHttpRequest object:

  • The response progress (XmlHttpRequest.onprogress)
    This is when the browser is downloading the data from the server.

  • The request progress (XmlHttpRequest.upload.onprogress)
    This is when the browser is sending the data to the server (including POST parameters, cookies, and files)

In your code you are using the response progress event, but what you need is the request progress event. This is how you do it:

    async: true,
    contentType: file.type,
    data: file,
    dataType: 'xml',
    processData: false,
    success: function(xml){
        // Do stuff with the returned xml
    type: 'post',
    url: '/fileuploader/' +,
    xhr: function(){
        // get the native XmlHttpRequest object
        var xhr = $.ajaxSettings.xhr() ;
        // set the onprogress event handler
        xhr.upload.onprogress = function(evt){ console.log('progress', evt.loaded/*100) } ;
        // set the onload event handler
        xhr.upload.onload = function(){ console.log('DONE!') } ;
        // return the customized object
        return xhr ;

The xhr option parameter must be a function that returns a native XmlHttpRequest object for jQuery to use.

Leave a Comment