View Single Post
Old 12-20-2012, 11:20 PM   PM User | #3
AndrewGSW
Senior Coder

 
Join Date: Apr 2011
Location: London, England
Posts: 2,120
Thanks: 15
Thanked 354 Times in 353 Posts
AndrewGSW will become famous soon enough
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>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>
        <td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</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>
__________________
"I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
Validate your HTML and CSS
AndrewGSW is offline   Reply With Quote