Star089 Star089 - 3 months ago 9
Ajax Question

Ajax request in for loop

I'd like to loop 100 times ajax request with for loop. This is my code :

for(var i=1; i<100; i++)
{
var num = i+1;

var request = new XMLHttpRequest();
request.open("GET", "http://localhost/test/1/2/main.php?t="+num+"", true);
request.send(null);
request.onreadystatechange = function() {

if (request.readyState == 4) {

var parser = new DOMParser();
var doc = parser.parseFromString(request.responseText, "text/html");

var rows = doc.getElementsByTagName("table")[0].getElementsByTagName("tbody")[0].getElementsByTagName("tr");

var sum = 0;
for(var j=0; j<rows.length;j++)
{
sum += parseInt( rows[j].getElementsByTagName("td")[7].textContent.trim() );
}
alert(num);
}


}


}

But it's not working.
In console I see 100 times this information:


XHR finished loading: GET "http://localhost/test/1/2/main.php?t=2".
XHR finished loading: GET "http://localhost/test/1/2/main.php?t=3".


Etc. So everything should be ok.
But I see alert only 14 times (I don't now why 14),no 100.

Why this program not working?

Answer

Please below code. Which will allow to fire ajax call only after previous has been completed. So no ajax call will missed.

<script type="text/javascript">    
    var num = 0;
    doAjax(0);
    function doAjax(arrCount) 
    {
        if(num<100){
            num += 1;
            var request = new XMLHttpRequest();
            request.open("GET", "http://localhost/test/1/2/main.php?t="+num+"", true);
            request.send(null);
            request.onreadystatechange = function() {
                if (request.readyState == 4) {
                    var parser = new DOMParser();
                    var doc = parser.parseFromString(request.responseText, "text/html");
                    var rows = doc.getElementsByTagName("table")[0].getElementsByTagName("tbody")[0].getElementsByTagName("tr");
                    var sum = 0;
                    for(var j=0; j<rows.length;j++)
                    {
                        sum += parseInt( rows[j].getElementsByTagName("td")[7].textContent.trim() );
                    }
                    alert(num);
                    doAjax(num)
                }
            }
        }       
    }
</script>
Comments