Skip to content

Instantly share code, notes, and snippets.

@keriati
Created March 25, 2014 10:42
Show Gist options
  • Save keriati/9759016 to your computer and use it in GitHub Desktop.
Save keriati/9759016 to your computer and use it in GitHub Desktop.
$.ajax upload progress event callback support
(function () {
// support for uploadProgress callback
var originalXHR = $.ajaxSettings.xhr;
$.ajaxSetup({
xhr: function () {
var myXHR = originalXHR();
if (myXHR.hasOwnProperty('upload') && this.hasOwnProperty('uploadProgress')) {
myXHR.upload.addEventListener('progress', this.uploadProgress, false);
}
return myXHR;
}
});
// Example request
function onUploadProgress(e) {
console.log((e.loaded / e.total) * 100 | 0);
}
function onSuccess() {
console.log('request over');
}
var file = $('input[type="file"]')[0].files[0],
myFormData = new FormData();
myFormData.append(file.name, file);
$.ajax({
url: 'http://yoururl',
timeout: 120000,
method: 'post',
processData: false,
cache: false,
contentType: false,
data: myFormData,
uploadProgress: onUploadProgress,
success: onSuccess
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment