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
  • Star 18 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • 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
}
});
@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