dependent dropdown in php – How to make dependent dropdown list using jquery Ajax?

dependent dropdown in php using ajax is the most popular feature of Web development. jQuery AJAX request parse the JSON response and convert it into an array.

dependent dropdown in php

HTML form with dependent dropdown select box is used to auto-populate the dependent data in the dropdown list.

Step 1: Create Tables and Dummy Data

CREATE TABLE `example_category` (
  `id` int(11) NOT NULL,
  `name` varchar(155) NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

example_sub_cat table:

CREATE TABLE `example_sub_cat` (
  `id` int(11) NOT NULL,
  `category_id` int(12) NOT NULL,
  `name` varchar(155) NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Now, in your database, you will have two tables “example_category” and “example_sub_cat”. Now we require to add some dummy data in both table like as bellow image.

Read Also:  Laravel Toggle Switch Inside Bootstrap Ajax Example

Step 2: Create index.php file

<!DOCTYPE html>
<html>
<head>
    <title>PHP - How to make dependent dropdown list using jquery Ajax? - www.pakainfo.com</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <link rel="stylesheet" href="plugin/bootstrap-3.min.css">
</head>
<body>


<div class="container">
    <div class="panel panel-default">
      <div class="panel-heading">Select category and get bellow Related sub_cat</div>
      <div class="panel-body">
            <div class="form-group">
                <label for="title">Select category:</label>
                <select name="category" class="form-control">
                    <option value="">--- Select category ---</option>

                    <?php
                        require('connect_db.php');
                        $sql = "SELECT * FROM example_category"; 
                        $result = $mysqli->query($sql);
                        while($dataResult = $result->fetch_assoc()){
                            echo "<option value='".$dataResult['id']."'>".$dataResult['name']."</option>";
                        }
                    ?>

                </select>
            </div>


            <div class="form-group">
                <label for="title">Select sub_cat:</label>
                <select name="sub_cat" class="form-control" style="width:350px">
                </select>
            </div>
      </div>
    </div>
</div>


<script>
$( "select[name='category']" ).change(function () {
    var categoryID = $(this).val();

    if(categoryID) {
        $.ajax({
            url: "do_process.php",
            dataType: 'Json',
            data: {'id':categoryID},
            success: function(data) {
                $('select[name="sub_cat"]').empty();
                $.each(data, function(key, value) {
                    $('select[name="sub_cat"]').append('<option value="'+ key +'">'+ value +'</option>');
                });
            }
        });


    }else{
        $('select[name="sub_cat"]').empty();
    }
});
</script>


</body>
</html>

Step 3: Add DB Configuration File

connect_db.php

<?php

define (DB_USER, "root");
define (DB_PASSWORD, "[email protected]#$iutjmnth");
define (DB_DATABASE, "mainexample");
define (DB_HOST, "localhost");
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
?>

Don’t Miss : Dependent Dropdown Example In PHP MySQL

Read Also:  jquery change event with select box, radio button and checkbox

Step 4: Add Ajax File

do_process.php

<?php

   require('connect_db.php');

   $sql = "SELECT * FROM example_sub_cat
         WHERE category_id LIKE '%".$_GET['id']."%'"; 

   $result = $mysqli->query($sql);

   $json = [];
   while($dataResult = $result->fetch_assoc()){
        $json[$dataResult['id']] = $dataResult['name'];
   }

   echo json_encode($json);
?>

I hope you get an idea about dependent dropdown in php.
I would like to have feedback on my infinityknow.com.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.