Home > Uncategorized > #Jquery #Ajax progress indicator

#Jquery #Ajax progress indicator

68747470733a2f2f7261772e6769746875622e636f6d2f4b656e616469612f63697263756c61722d70726f67726573732d696e64696361746f722f6d61737465722f73637265656e73686f742e706e67

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

Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: