Skip to content

Instantly share code, notes, and snippets.

@nebirhos
Forked from db/jquery.ajax.progress.js
Created October 15, 2012 11:26
Show Gist options
  • Save nebirhos/3892018 to your computer and use it in GitHub Desktop.
Save nebirhos/3892018 to your computer and use it in GitHub Desktop.
add XHR2 upload and download progress events to jQuery.ajax
(function addXhrProgressEvent($) {
var originalXhr = $.ajaxSettings.xhr;
$.ajaxSetup({
xhr: function() {
var req = originalXhr(), that = this;
if (req) {
if (typeof req.addEventListener == "function" && that.progress !== undefined) {
req.addEventListener("progress", function(evt) {
that.progress(evt);
}, false);
}
if (typeof req.upload == "object" && that.progressUpload !== undefined) {
req.upload.addEventListener("progress", function(evt) {
that.progressUpload(evt);
}, false);
}
}
return req;
}
});
})(jQuery);
// usage:
// note, if testing locally, size of file needs to be large enough
// to allow time for events to fire
$.ajax({
url: "./json.js",
type: "GET",
dataType: "json",
complete: function() { console.log("Completed."); },
progress: function(evt) {
if (evt.lengthComputable) {
console.log("Loaded " + parseInt( (evt.loaded / evt.total * 100), 10) + "%");
}
else {
console.log("Length not computable.");
}
},
progressUpload: function(evt) {
// See above
}
});
@susamcsx
Copy link

susamcsx commented May 4, 2014

hi,i test your code ,but i find that the code "console.log("Loaded " + parseInt( (evt.loaded / evt.total * 100), 10) + "%");" just only log one time,it just print out "100%" only.how can i do

@yasu47b
Copy link

yasu47b commented Jun 10, 2015

Thanks nebirhos, thanks!

To susamcsx

just only log one time,it just print out "100%" only.how can i do

I just tested his code and printed out "0%" and "100%" at first.

But after I limited the bandwidth on Apache2 using mod-bw,
console.log shows like that "Loaded 2%, 4%, 6%, 8%, 11%, ... , Loaded 100%".

So I suggest if you test this code, you had better handle large data or set band limitation.

thanks helpful code!

@hbriceno
Copy link

hbriceno commented Sep 3, 2015

Just for information, I have tested this on many browsers configurations and I have found the following:
with jQuery 1.7.2 it works fine. with jQuery 1.11.3 it works fine, except that on IE11 on Win8 it breaks, meaning my CORS $.ajax request get permission denied.

@hbriceno
Copy link

hbriceno commented Sep 3, 2015

Found the bug, you want to replace:
var req = originalXhr(), that = this;
with:
var that = this;
var req = originalXhr.bind(that)()

The problem is that the original XHR, in 1.7.2 used this.isLocal to choose, but since it is undefined, it will do the right thing... in 1.11.3 there is another condition this.type to choose between ActiveXHR and StandardXHR, thus without rebinding this.type it seems it does not choose the right one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment