Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to get jQuery ajax upload progress?

Tags:

jquery

ajax

$.ajax({
  xhr: function()
  {
    var xhr = new window.XMLHttpRequest();
    //Upload progress
    xhr.upload.addEventListener("progress", function(evt){
      if (evt.lengthComputable) {
        var percentComplete = evt.loaded / evt.total;
        //Do something with upload progress
        console.log(percentComplete);
      }
    }, false);
    //Download progress
    xhr.addEventListener("progress", function(evt){
      if (evt.lengthComputable) {
        var percentComplete = evt.loaded / evt.total;
        //Do something with download progress
        console.log(percentComplete);
        }
      }, false);
    return xhr;
  },
  type: 'POST',
  url: "/",
  data: {},
  success: function(data){
    //Do something success-ish
  }
});

This does not work on jQuery 1.5+ because the xhr is replaced by the jqXHR (i.e. a high level version of the raw XHR.) Now the question is how to get it to work with jqXHR… Anyone know how to do it?

like image 449
Jin Lin Avatar asked Nov 02 '12 21:11

Jin Lin


People also ask

Is AJAX better than jQuery?

While JQuery is a library for better client-side web page development, AJAX is a technique of doing XMLHttpRequest to the server from the web page and sending/retrieving data used on a web page. AJAX can change data without reloading the web page. In other words, it implements partial server requests.


1 Answers

Try this

$.ajax({
    url: path,
    xhr: function () {
        var xhr = $.ajaxSettings.xhr();
        xhr.upload.onprogress = function (e) {
            if (e.lengthComputable) {
                console.log(e.loaded / e.total);
            }
        };
        return xhr;
    }
}).done(function (e) {

})
like image 186
Luke Madhanga Avatar answered Sep 28 '22 01:09

Luke Madhanga