-1

I have a java script function that gets a string that represents a number, loops and returns the same value (max value) inside jquery function:

            function auto_tag_posts(data) {
                //data is 999
                var p_nr=0;
                for (p_nr=0; p_nr<data; p_nr++) {
                    $.post("./myphp.php", {command: "c"}, function(post_data){
                        //p_nr is 999!!! WHY?
                        alert(p_nr);
                    }); 
                }

What's the fix?

The problem was that there were made 999 requests in a split second, the answers were coming in time, but the jquery "for" was finished instantly.

Cumatru Cosu
  • 103
  • 2
  • 7

1 Answers1

3

That's because of closures. Use these c0dez instead

for (p_nr=0; p_nr<data; p_nr++) {
    (function(p_nr) {}
        $.post("./myphp.php", {command: "c"}, function(post_data){
            //p_nr is 999!!! WHY?
            alert(p_nr);
        }); 
    )(p_nr);
}
zerkms
  • 249,484
  • 69
  • 436
  • 539