Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refresh dropdown without page refresh?

Tags:

php

mysql

I am having following difficulties:

I am fetching value of dropdown from the mysql and I want that information to be displayed in that dropdown list.

See 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>

By using this code I am populating the values from database to dropdown list, but for this I need to refresh the page for values to get displayed.

Thank you.

like image 490
Jeet Dholakia Avatar asked Jul 08 '15 11:07

Jeet Dholakia


1 Answers

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>';
            }
like image 122
Arun Kumar Avatar answered Oct 08 '22 09:10

Arun Kumar