How to Dynamic Select Option Menu Using Ajax, Mysql and PHP

In this tutorial, we will show you how to implement relational dropdown of state to city using jQuery, Ajax, PHP, and MySQL. Means state is related to city. Based on changing of state & city will be fetched from the database without reloading the page using jQuery, Ajax, PHP, and MySQL. You may also like How to Dynamic PHP and html form with qty price and total in table using JavaScript calculations and How to create cache dynamic pages using PHP

HTML, jQuery and PHP Code

<?php
define('DB_SERVER', "localhost");
define('DB_USER', "root");
define('DB_PASS', "");
define('DB_DATABASE', "whatsappdwld_db");
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
?>

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script type="text/javascript">
            function fetch_select(val)
            {
                $.ajax({
                    type: 'post',
                    url: 'fetch.php',
                    data: {
                        get_option: val
                    },
                    success: function (response) {
                        document.getElementById("new_select").innerHTML = response;
                    }
                });
            }

        </script>

    </head>
    <body>
        <p>How to Dynamic Select Option Menu Using Ajax, Mysql and PHP</p>
        <select onchange="fetch_select(this.value);">
            <option>Select state</option>
            <?php
            $select = mysqli_query($con,"SELECT state FROM places GROUP BY state");
            while ($row = mysqlI_fetch_assoc($select)) {
                echo "<option>" . $row['state'] . "</option>";
            }
            ?>
        </select>

        <select id="new_select"></select>
    </body>
</html>

PHP Code (fetch.php)

<?php
define('DB_SERVER', "localhost");
define('DB_USER', "root");
define('DB_PASS', "");
define('DB_DATABASE', "whatsappdwld_db");
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);


if(isset($_POST['get_option']))
{
    $state = $_POST['get_option'];
    $find=mysqli_query($con,"SELECT city FROM places WHERE state='$state'");
    while($row=mysql_fetch_array($find))
    {
        echo "<option>".$row['city']."</option>";
    }
}
?>

Leave a Reply

Your email address will not be published. Required fields are marked *