1

I have a problem with using AJAX and FOR loop. In PHP file is a few if which dependly of number (1-9) returns echo with a price.

f.ex.

1 -> echo "15.20";
2 -> echo "11.10";
3 -> echo "13.65";
4 -> echo "14.30";

JS Script:

for(i=1; i<10; i++)
{
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementsByClassName("courierprice")[i-1].innerHTML = xmlhttp.responseText;
        }
        else
        {
            document.getElementsByClassName("courierprice")[i-1].innerHTML = "shit";
        }
    }
    xmlhttp.open("GET", "gethint.php?q=" + i , true);
    xmlhttp.send();
}

When there is no loop, and just a var i = 1, it returns correctly (15.20), but if I want to do it couple of times, I just got in all classes "shit".

If you got any advice how to do it, please let me know. Thanks!

R3tep
  • 12,512
  • 10
  • 48
  • 75
Karol Gasienica
  • 2,825
  • 24
  • 36

1 Answers1

2

You should wrap your whole loop content in a function and pass the i there.

for(i=1; i<10; i++) {
        (function (i) {

            ...your async code...

        })(i);
}
Andrius
  • 5,934
  • 20
  • 28