Dynamic dependent dropdown means data of child dropdown will change according to the selection of its parent dropdown. The data in child dropdown populated based on the item selected from its parent dropdown without refreshing the page. This scenario commonly used for state-city binding and category-subcategory binding.

So, this blog will explain you how to make dynamic dependent dropdown in Core PHP by using Ajax with JQuery and MySQL database. Here I have taken a relational example of State-City to implement. City data will be fetched from database according to the selection of State from dropdown without refreshing page.

To implement example we need two tables 1. State (Columns: StateId, StateName) and 2. City (Columns: CityId, StateIdFK, CityName). In state StateId is a primary key and in city table StateIdFK is a foreign key.

Using Ajax - $.ajax() call

Step 1. To fetch data from database using Ajax we have to create web service which is called using its url in Ajax call and return data according to selected state. So first create web service to fetch data.

getstatewisecity.php

<?php

    $con = new mysqli("localhost", "root", "", "demo") or die(mysqli_error($con));

    

    $state_id = $_REQUEST['state_id'];

    $query    = "select * from tblcity where StateIdFk = '" . $state_id . "'";

    

    $result = $con->query($query);

?>

<select name="chCity">

    <option>----------Select City----------</option>

    <?php

        while ($row = mysqli_fetch_array($result))

        {

    ?>

       <option value=<?php echo $row['CityId']; ?>><?php echo $row['CityName']; ?></option>

    <?php

        }

    ?>

</select>

Step 2. Now create ajaxstatecity.php file which contains a user interface and Ajax call of web service. Ajax will call web service onchange() event of state dropdown and stated will be pass with request using data parameter of $.ajax.

ajaxstatecity.php  

<?php

    $con = new mysqli("localhost", "root", "", "demo") or die(mysqli_error($con));

?>

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Ajax PHP Demo</title>

    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

    <script type="text/javascript">

    /* JQuery to bind City according to State selection */

    $(document).ready(function () {

        $('#drpstate').change(function () {

            var state_id = $('#drpstate').val();

            if (state_id != '') {

                $.ajax({

                    url: "getstatewisecity.php",

                    method: "POST",

                    data: { state_id: state_id },

                    success: function (data) {

                        $('#drpcity').html(data);

                    }

                });

            }

            else {

                $('#city').html('<option value="">Select City</option>');

            }

        });

    });

</script>

</head>

<body>

    <center>

        <form method="post">

           <h1>Ajax PHP Demo</h1>

            <table border="1">

                <tr>

                    <td>State</td>

                    <td>

                        <select name="drpstate" id="drpstate">

                            <option>----------Select State----------</option>

                            <?php

    $res = $con->query("select * from state");

    while ($row = mysqli_fetch_array($res))

    {

    ?>

                            <option value="<?php echo $row["StateId"]; ?>"><?php echo $row["StateName"]; ?></option>

                            <?php

    }

    ?>

                       </select>

                    </td>

                </tr>

                <tr>

                    <td>City</td>

                    <td>

                        <select name="" id="drpcity">

                            <option>----------Select City----------</option>

                        </select>

                    </td>

                </tr>

            </table>

        </form>

    </center>

</body>

</html>

Using XMLHttpRequest

XMlHttpRequest (XHR) is an API which is used by Javascript and JQuery to transfer and retrieve data from server using HTTP request. It creates independent connection between client and server to request and response data in XML format.

So, now we use XMLHttpRequest to populate city dropdown as per state. Same as above, we have to create two files, one for web service and second .php. Web service file will remain same and only ajaxstatecity.php file will change.

ajaxstatecity.php

<?php

    $con = new mysqli("localhost", "root", "", "demo") or die(mysqli_error($con));

?>

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Ajax PHP Demo</title>

    <script type="text/javascript">

            function getXMLHTTP() { 

                var xmlhttp=false;    

                try{

                    xmlhttp=new XMLHttpRequest();

                }

                catch(e)    {        

                    try{            

                        xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");

                    }

                    catch(e){

                        try{

                        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");

                        }

                        catch(e1){

                            xmlhttp=false;

                        }

                    }

                }

                return xmlhttp;

            }

            function getProject(state_id) {        

                var strURL="getstatewisecity.php?state_id="+state_id;

                var req = getXMLHTTP();

                if (req) {

                    req.onreadystatechange = function() {

                        if (req.readyState == 4) {

                            /* only if "OK" */

                            if (req.status == 200) {    

                                document.getElementById('drpcity').innerHTML=req.responseText;                        

                            } else {

                                alert("Problem while using XMLHTTP:\n" + req.statusText);

                            }

                        }                

                    }            

                    req.open("GET", strURL, true);

                    req.send(null);

                }        

            }

        </script>

</head>

<body>

    <center>

        <form method="post">

           <h1>Ajax PHP Demo</h1>

            <table border="1">

                <tr>

                    <td>State</td>

                    <td>

                        <select name="drpstate" id="drpstate" onchange="getProject(this.value)">

                            <option>----------Select State----------</option>

                            <?php

    $res = $con->query("select * from state");

    while ($row = mysqli_fetch_array($res))

    {

    ?>

                            <option value="<?php echo $row["StateId"]; ?>"><?php echo $row["StateName"]; ?></option>

                            <?php

    }

    ?>

                       </select>

                    </td>

                </tr>

                <tr>

                    <td>City</td>

                    <td>

                        <select name="" id="drpcity">

                            <option>----------Select City----------</option>

                        </select>

                    </td>

                </tr>

            </table>

        </form>

    </center>

</body>

</html>

Output