| | Stumble It! | Add to Mixx! | | diigo it | | Slashdot |

Tuesday, March 2, 2010

Simple AJAX Progress Bar

Below is some sample code that I'm posting to help point other developers in the right direction when attempting to create a progress bar for an AJAX function. This isn't 100% or even cross-browser compatible exactly, but I have tested it successfully on the current stable Chrome release.

Say you have a 'for' loop that runs an AJAX function for every item in an array and you want to view the progress of the function. Here's how I solved that problem:
<html>
<head>
<title>
</title>
<script type='text/javascript'>
function startAjax() {
// ... define yourArray[] for AJAX processing
for (var i=0;i<yourArray.length;i++) {
// loop through each item in the array and perform an AJAX process on it.
setTimeout('onReadyStateChangeFn("'+(Number(i)/Number(yourArray.length))*100+'%")',1000);
}
}

function onReadyStateChangeFn(perc) {
// ...
if (ajaxObj.readyState == 4 && ajax.status == 200) {
// ... your ajax-handling code here
document.getElementById('pbar_bar').style.width = perc;
// ... any additional code
}
}
</script>
</head>
<body>
<div id='pbar_frame' style='background:red;border:1px black solid;width=100%;height:1em;'>
<div id='pbar_bar' style='background:lime;width:0%;height:1em;'></div>
</div>
</body>
</html>
The key ingredient was 'setTimeout()', without it, the page would appear to hang while the 'for' loop executed.

Enjoy!

0 comments: