The following version handles errors in the requests, and it forces 404 failures on every other request to demonstrate.
Code:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<style type="text/css">
#theTable { outline: 1px solid gray; }
#theTable td {
width: 50px; height: 50px;
}
</style>
</head>
<body>
<h1>10 Asynchronous Ajax Requests</h1>
<p>Here come the 10 random numbers..</p>
<div id="theDiv">Wait..</div>
<table id="theTable" summary="the data">
<tr><td> </td><td> </td><td> </td><td> </td><td> </td>
<td> </td><td> </td><td> </td><td> </td><td> </td></tr>
</table>
<script type="text/javascript">
function fncTrim(str) {
return str.replace(/^\s+|\s+$/g,'');
}
function insertData(index, value) {
insertData.tbl = insertData.tbl || document.getElementById('theTable');
insertData.tbl.rows[0].cells[index].firstChild.data = value;
}
var cycle = 10; // total number of requests
for (var i=0; i < cycle; i++) {
var counter = 1, vals = [];
(function (req, items, func) {
var thisone = i;
req.onreadystatechange = function () {
if (req.readyState == 4) {
if (req.status == 200) {
vals.push(thisone, fncTrim(req.responseText) * 1);
if (++counter == Math.floor(items / 2)) {
// start displaying in the table
updating = setInterval(function () {
if (vals.length > 0) {
func(vals.shift(), vals.shift());
} else if (counter > items) {
clearInterval(updating);
}
}, 500);
}
} else {
func(thisone, "Err!" + req.status);
}
}
};
if (thisone % 2) {
req.open("GET", 'createRandomNumber.php?rnd=' + Math.random(), true);
} else {
req.open("GET", 'DoesNotExist.php?rnd=' + Math.random(), true);
}
req.send(null);
}) (new XMLHttpRequest() || new ActiveXObject("Microsoft.XMLHTTP"), cycle, insertData);
}
</script>
</body>
</html>