How to update the drop-down list without refreshing the page?

I have the following difficulties:

I am extracting the value of a dropdown from mysql and want this information to appear in this dropdown.

Watch this:

<select id="location" name="location" class='form-control'>
    <option value="0">Select location</option>
        <?php
            $query = mysql_query("select cityname from city");
                while($row = mysql_fetch_assoc($query))
                {
                    echo '<option value="'.$row['cityname'].'">'.$row['cityname']. '</option>';
                }
        ?>
</select>

Using this code, I populate the values ​​from the database into a drop-down list, but for this I need to refresh the page for the values ​​that will be displayed.

Thank.

+4
source share
1 answer

Use jQuery Ajax

yourfile.php

<select id="location" onchange="getState(this.value)" name="location" class='form-control'>
<option value="0">Select location</option>
    <?php
        $query = mysql_query("select * from city");
            while($row = mysql_fetch_assoc($query))
            {
                echo '<option value="'.$row['cityid'].'">'.$row['cityname']. '</option>';
            }
    ?>
</select>

<select id="state">

</select>

JQuery Script

function getState(city_id)
{
    var html = $.ajax({
        type: "POST",
        url: "path/to/ajax/my_ajax.php",
        data: "city_id=" +city_id,
        async: false
    }).responseText;
    if(html){
        $("#state").html(html);
    }
}

ajax.php

$query = mysql_query("select * from state where city_id=".$_REQUEST['city_id']);
            while($row = mysql_fetch_assoc($query))
            {
                echo '<option value="'.$row['state_id'].'">'.$row['state_name']. '</option>';
            }
+3
source

All Articles