View Single Post
Old 12-17-2012, 09:59 PM   PM User | #1
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
Smooth async requests

When requesting a sequence of data asynchronously using ajax the data is not returned at regular intervals, or necessarily in the order the requests were made. The following code uses setInterval to update the page at regular intervals - creating a smooth page-update. The data is inserted into table cells according to the order the data was received.

The setIntervals are not initiated until half the data has been received, and will be cleared when all data has been processed. (An else clause could be added so that the setInterval is cleared if there is an error in retrieving the remaining data.)

asyncAjax.html
Code:
<!DOCTYPE html>
<html>
<head>
    <title>Page Title</title>
<style type="text/css">
    #theTable { outline: 1px solid gray; }
    #theTable td {
        width: 40px; 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(vals) {
    this.tbl = this.tbl || document.getElementById('theTable');
    tbl.rows[0].cells[vals.shift()].firstChild.data = vals.shift();
}

for (var i=0; i < 10; i++) {
    var counter = 1, vals = [];
    (function (req, items, func) {
        var thisone = i;
        req.onreadystatechange = function () {
            if (req.readyState == 4 && 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);
                            
                        } else if (counter > items) {
                            clearInterval(updating);
                        }
                    }, 500);
                }
            }
        };
        req.open("GET", 'createRandomNumber.php?rnd=' + Math.random(), true);
        req.send(null);
    }) (new XMLHttpRequest() || new ActiveXObject("Microsoft.XMLHTTP"), 10, insertData);
}

</script>
</body>
</html>
createRandomNumber.php
PHP Code:
<?php
sleep
(1);   // 1 second
echo rand(1100);
?>
I suspect that this is more instructional, and hopefully interesting , than directly applicable. [This follows from a recent thread which triggered my interest.]
__________________
"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

Last edited by AndrewGSW; 12-17-2012 at 10:04 PM..
AndrewGSW is offline   Reply With Quote