0

I am running a code

<div id="#1gr1">Kun</div>


 for(var i=1;i<=10;i++){
  $.ajax({
                type: "POST",
                url: "get_url.php",
                async: false,
                data: {a: 'hi'}
            }).done(function(msg) {

               //   getting msg[1]='Good';

                if (msg !== '') {
                    $('#1gr' + i).html(msg[1]);

                }                 

                msg='';

            });

  }

It is changing html of #1gr1 temporarily to "Good"

<div id="#1gr1">Good</div>

but at next call when i=2;it is changing text of #1gr1 to back "KUN".
and this time changing html for #1gr2

  <div id="#1gr1">Kun</div>
  <div id="#1gr2">Good</div>

MAIN PROBLEM:Why text of div automatically changing back to original text,Value of i as exactly what i want.

Any Guess..?

Confused
  • 1,602
  • 15
  • 25
  • 1
    Ajax = Asynchronous Javascript. Your i would have already changed by the time the ajax call completes. – TJ- Mar 19 '14 at 12:33
  • Might be related to the infamous Javascript loop: http://stackoverflow.com/questions/1451009/javascript-infamous-loop-issue –  Mar 19 '14 at 12:33
  • There's no guarantee that these multiple AJAX calls are going to complete in the same order that they're invoked. – David Mar 19 '14 at 12:34
  • @EmanuelSaringan Please check edit "Main Problem".Why text of div automatically changing back to original text,Value of i as exactly what i want. – Confused Mar 19 '14 at 12:43
  • @CBroe Please check edit "Main Problem".Why text of div automatically changing back to original text,Value of i as exactly what i want. – Confused just now edit – Confused Mar 19 '14 at 12:44

2 Answers2

2

just clean your code remove # from id dom

<div id="#1gr1">Kun</div>

to

<div id="1gr1">Kun</div>
rjdmello
  • 865
  • 2
  • 9
  • 14
0

You don't seem to have a proper understanding about AJAX - Asynchronous Javascript and XML.

So, in your code, the for loop executes normally.

But the .done() is only called after an ajax request is done.

Also, you cannot guarantee the order of execution when it comes to $.ajax

Lets, take the example below:

$.ajax({
url:'/some/resource.xml'
});
$.ajax({
url:'/some/json'
});

In the above case, you cannot guarantee that resource.xml will be finished first. Also, you cannot guarantee that json will always, come second.

In each case, whichever responds fast and is lightweight, will be the winner.

So, to conclude, loops aren't running in an unexpected behavior.

Also you are using ids starting with #, which confuses jquery.

Amit Joki
  • 58,320
  • 7
  • 77
  • 95