TheCodeNovice
TheCodeNovice

Reputation: 690

Multiple xmlhttp requests causes readystate not to reach 4 for all but the last instance.

Perplexed by this issue of my xmlhttp failing to complete. The issue only arises when I have multiple calls. Oddly enough only the last one completes. I feel as if the first one times out or something. In watching the code in the window the ready state change function fires a few times but the value is always 1 and eventually it jumps out and performs the next call. Is there a way of fixing this? MAybe adding a delay? Any advice is much apprecaited.

 <script>    
<!--var plant_select = document.createElement("select");  -->
             var datafile = '';
             var xmlhttp = new XMLHttpRequest();

             xmlhttp.open("GET","http://localhost:8080/res/plants.csv",true);
             xmlhttp.send();
             xmlhttp.onreadystatechange = function()
             {
                if(xmlhttp.status==200 && xmlhttp.readyState==4)
                {
                    processCSV(xmlhttp.responseText, document.getElementById("plant_select"),"Select Plant");
                }
             }
        </script>
        </select>
    </div>
    <div class="menu_element" id="plantType_div">
        <select  class="Menu" id="plantType_select">
        <script>
             <!--var plant_select = document.createElement("select");  -->
             var datafile = '';
             var xmlhttp = new XMLHttpRequest();

             xmlhttp.open("GET","http://localhost:8080/res/planttypes.csv",true);
             xmlhttp.send();
             xmlhttp.onreadystatechange = function()
             {
                if(xmlhttp.status==200 && xmlhttp.readyState==4)
                {
                    processCSV(xmlhttp.responseText, document.getElementById("plantType_select"),"Select Plant Type");
                }
             }
        </script>

Upvotes: 0

Views: 330

Answers (2)

Quentin
Quentin

Reputation: 943686

You are using the same, global variable for each request: var xmlhttp. Each subsequent instance then tries to operate on the same variable. So you will only get the last one because that was the last value of the variable to be written before any of the responses got back.

Wrap each instance in a function so you are dealing with locally scoped variables instead of globals.

Upvotes: 1

opalenzuela
opalenzuela

Reputation: 3171

You are using the same object every time:

 var xmlhttp = new XMLHttpRequest(); 

Try to give a different name for each request.

Upvotes: 1

Related Questions