In plain javascript is very simple: need just to attach the callback to {XMLHTTPRequest}.onprogress
var xhr = new XMLHttpRequest();
xhr.onprogress = function(e){
if (e.lengthComputable)
var percent = (e.loaded / e.total) * 100;
};
xhr.open('GET', 'http://www...', true);
xhr.onreadystatechange = function() {
...
};
xhr.send(null);
but I'm doing an ajax site that download html data with JQuery ($.get()
or $.ajax()
) and I was wondering which is the best way to get the progress of a request in order to display it with a little progress bar but curiously, I'm not finding anything usefull in JQuery documentation...
jQuery has an
AjaxSetup()
function that allows you to register global ajax handlers such asbeforeSend
andcomplete
for all ajax calls as well as allow you to access thexhr
object to do the progress that you are looking forjQuery has already implemented promises, so it's better to use this technology and not move events logic to
options
parameter. I made a jQuery plugin that adds progress promise and now it's easy to use just as other promises:Check it out at github
Something like this for
$.ajax
(HTML5 only though):I tried about three different ways of intercepting the construction of the Ajax object:
xhrFields
, but that only allows for one listener, only attaches to download (not upload) progress, and requires what seems like unnecessary copy-and-paste.progress
function to the returned promise, but I had to maintain my own array of handlers. I could not find a good object to attach the handlers because one place I'd access to the XHR and another I'd have access to the jQuery XHR, but I never had access to the deferred object (only its promise).ajax
with my own. The only potential shortcoming is you can no longer use your ownxhr()
setting. You can allow for that by checking to see ifoptions.xhr
is a function.I actually call my
promise.progress
functionxhrProgress
so I can easily find it later. You might want to name it something else to separate your upload and download listeners. I hope this helps someone even if the original poster already got what he needed.http://www.htmlgoodies.com/beyond/php/show-progress-report-for-long-running-php-scripts.html
I was searching for a similar solution and found this one use full.
}
and your server outputs