for loop inside onreadystatechange function

Discussion in 'JavaScript' started by FunkyFresh, Aug 14, 2011.

  1. #1
    
    				ajaxRequest.onreadystatechange = function(){
    					if(ajaxRequest.readyState == 4 && ajaxRequest.status==200){  
    						var tx2 = ajaxRequest.responseText;
    						
    						var selectedItem = "";
    						for (i =0; i< listCounter; i++){
    							selectedItem = "list#" +x;
    							formElmts[selectedItem].innerHTML = tx2;
    						}
    					}
    				}
    
    Code (markup):
    The code is suppose to change multiple drop down lists with the same text is returned from ajaxRequest.responseText.

    why dont for loops work inside of onreadystatechange? I have been researching and it seems its because its asynchronous.
    Any tips on how to make it work.
     
    FunkyFresh, Aug 14, 2011 IP
  2. JohnnySchultz

    JohnnySchultz Peon

    Messages:
    277
    Likes Received:
    4
    Best Answers:
    7
    Trophy Points:
    0
    #2
    What does the result look like after the ajax call?
     
    JohnnySchultz, Aug 15, 2011 IP
  3. tiamak

    tiamak Active Member

    Messages:
    81
    Likes Received:
    2
    Best Answers:
    3
    Trophy Points:
    58
    #3
    what are listCounter and x values, are u sure that this vars are accessible inside your function?
    my bet is that u set those vars in wrong place or wrong way and ur function simply doesnt have access to them.
     
    tiamak, Aug 15, 2011 IP
  4. FunkyFresh

    FunkyFresh Peon

    Messages:
    499
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #4
    The result was it only edited the first element only. I researched it said something with the queue. I tried it with a while loop instead and it magically worked. Not sure why but it works for now.

    Any ideas how to fix it or a legit way around it?
     
    FunkyFresh, Aug 18, 2011 IP