I’ve been busy with some AJAX code. I want to calculate how much data has been loaded and I want to display it with percents.
All my preloaded info is inside “feedback”.
Can I calculate how much DATA it contains (in bytes) and can I also view the progress? Like when it has loaded: 10kb, 20kb, 30kb etc
My code:
function calc(page)
{
$('#pageLoad h2').animate({ marginTop : '0px'}, 200);
$.ajax(
{
url: './pages/page.php',
type: 'POST',
data: 'page='+page,
success: function( feedback )
{
$('#content').html( feedback );
}
});
};
Sorry for my poor english.
It is possible. XHRs have a
progressevent. The only problem is accessing the XHR object – unfortunatelybeforeSendonly receives thejqXHRobject and not the underlying XHR object. It is also not accessible as a property of the wrapper. You can however hook into the creation process of the XHR object by adding the following option to$.ajax():Here’s my initial solution. It is extremely hard to combine with jQuery since you can’t easily hook into the onreadystatechange handler and cannot safely replace it after it has been set:
You need to add a customonreadystatechangehandler. When thereadyStateof the XHR object becomes2(*HEADERS_RECEIVED*) you can access theContent-Lengthheader to get the total size and then wait for the event to fire withxhr.readyState == 3(LOADING).Then you can calculate the progress by looking at
xhr.responseText.length.However, this will only fire once. So you need to start a timer (using
setInterval()) which will check the ready state and response size e.g. every 100 msecs. As soon as the request finishes you stop the interval again usingclearInterval().