#Jquery #Ajax progress indicator
If you are using JQuery Ajax to upload a file, or other large blob of data, you might want to show the user that something is happening, rather than just showing an animated gif.
Here’s a JQuery Plugin by Chad Engler which can extend the default $.ajax behavior to report progress updates as a percentage.
(function ($, window, undefined) {
//is onprogress supported by browser?
var hasOnProgress = (“onprogress” in $.ajaxSettings.xhr());//If not supported, do nothing
if (!hasOnProgress) {
return;
}//patch ajax settings to call a progress callback
var oldXHR = $.ajaxSettings.xhr;
$.ajaxSettings.xhr = function () {
var xhr = oldXHR.apply(this, arguments);
if (xhr instanceof window.XMLHttpRequest) {
xhr.addEventListener(‘progress’, this.progress, false);
}if (xhr.upload) {
xhr.upload.addEventListener(‘progress’, this.progress, false);
}return xhr;
};
})(jQuery, window);
To use it, you would write code allong the lines of:
Upload: function(data, callback, progressCallback)
{
var strUrl = “/Upload.aspx”;
$.ajax({
method: ‘POST’,
url: strUrl,
dataType: ‘json’,
data: {
Data: data
},
success: function (result)
{
callback(result);
},
error: function () { },
progress: function (e) {
if (e.lengthComputable) {
progressCallback(Math.round(e.loaded / e.total * 100));
}
}
});
}
I’ve just used this on the upload feature of https://httpsimage.com