rishav
rishav

Reputation: 481

Getting the latest value from a listbox which has been updated using AJAX

I'm using two listboxes, the 2nd one is updated by AJAX whenever the 1st listbox's value is changed. Now, based on the values of these two listboxes I need to create a table. But the problem is that my table is created with the old value of the 2nd listbox and not the latest.

Code:

<script>
function pop_to()
{
    var xmlhttp= new XMLHttpRequest();
    var from=document.getElementById("date_from").value;
    xmlhttp.onreadystatechange=function()
    {
        if(xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            document.getElementById("date_to").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","pop_to.php?from="+from,true);
    xmlhttp.send();
}

function update_sales_content()
{
    var xmlhttp= new XMLHttpRequest();
    var from=document.getElementById("date_from").value;
    var to=document.getElementById("date_to").value;
    var xmlhttp= new XMLHttpRequest();
    xmlhttp.onreadystatechange=function()
    {
        if(xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            document.getElementById("sales_data").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","sales_report.php?from="+from+"&to="+to,true);
    xmlhttp.send();
}

</script>

<body>  
<select id="date_from" onchange='pop_to();update_sales_content();' style="position:relative;left:730px;">
    <option>From</option>
    <?php 
        $sql="select distinct order_dt from cust_order order by order_dt";
        $result=mysql_query($sql,$con) or die(mysql_error());
        if($result)
        {
            while($rec=mysql_fetch_row($result))
            {
                echo"<option value='$rec[0]'>$rec[0]</option>";
            }

        }
    ?>
    </select>
    <select id="date_to" onchange='update_sales_content()' style="position:relative;left:800px;">
    </select>
<div id="sales_data">
</div>
</body>

Upvotes: 1

Views: 57

Answers (1)

Barmar
Barmar

Reputation: 781096

AJAX is asynchronous. When you do:

onchange='pop_to(); update_sales_content();'

you're running update_sales_content() immediately, not waiting for the AJAX response. You need to call it from the pop_to() callback function:

function pop_to()
{
    var xmlhttp= new XMLHttpRequest();
    var from=document.getElementById("date_from").value;
    xmlhttp.onreadystatechange=function()
    {
        if(xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            document.getElementById("date_to").innerHTML=xmlhttp.responseText;
            update_sales_content();
        }
    }
    xmlhttp.open("GET","pop_to.php?from="+from,true);
    xmlhttp.send();
}

Upvotes: 1

Related Questions