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 CodeIgniter 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. The page will not be refreshed because I have used JQuery and Ajax to implement it.

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.

Note: If you want to setup CodeIgniter, please visit my previous blog CRUD Operation in PHP CodeIgniter and MySQL database with example.

Controller

Create a controller in application-> controllers folder. Write a functions to bind state dropdown and city dropdown according to selection of state.

dropdownController.php  

<?php

    defined('BASEPATH') OR exit('No direct script access allowed');

    class dropdownController extends CI_Controller

    {

        function __construct()

        {

            parent::__construct();

            $this->load->helper('url'); /* load base url */

            $this->load->model('dropdownModel'); /* load model default which you create */

        }

        

        /* Load index page - State dropdown will be filed with data */

        public function index()

        {

            $data["fetch_statedata"] = $this->dropdownModel->fetchstatedata();

            $this->load->view("state", $data);

        }

        

        /* Function to fecth city according item selected in state dropdown */

        public function fetchcity()

        {

            if ($this->input->post('state_id'))

            {

                echo $this->dropdownModel->fetchstateidwisedata($this->input->post('state_id'));

            }

        }

    }

?>

Model

Create model in application->models folder. Create model for write query for fetch state and city data from database. Below the code of model.

dropdownModel.php  

<?php

    class dropdownModel extends CI_Model

    {

        /* fetch data of state */

        function fetchstatedata()

        {

            $this->db->select('*');

            $this->db->from('state');

            $query = $this->db->get();

            return $query->result();

        }

        

        /* fetch data of city respective state wise */

        public function fetchstateidwisedata($state_id)

        {

            $this->db->select('*');

            $this->db->from('tblcity');

            $this->db->where('StateFk', $state_id);

            $query  = $this->db->get();

            $output = '<option value="">----------Select City----------</option>';

            foreach ($query->result() as $row)

            {

                $output .= '<option value="' . $row->CityId . '">' . $row->CityName . '</option>';

            }

            return $output;

        }

    }

?>

Views

Now create dynamicdropdown.php view in application->views folder and write below code. 

dynamicdropdown.php

<!DOCTYPE html>

<html>

<head>

    <title>Demo Ajax</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

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

    <style>

        .txtcn {

            text-align: center;

        }

    </style>

</head>

<body>

    <center><h1>AutoSelection Dropdown</h1></center>

    <form method="post" enctype="multipart/form-data">

        <table border="1" align="center">

            <tr>

                <td>State</td>

                <td>

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

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

                        <?php

        foreach ($fetch_statedata as $row)

        {

?>

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

                <?php

        }

?>

                   </select>

                </td>

            </tr>

            <tr>

                <td>City</td>

                <td>

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

                        <option value="">----------Select City----------</option>

                    </select>

                </td>

            </tr>

        </table>

    </form>

</body>

</html>

<script>

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

    $(document).ready(function () {

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

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

            if (state_id != '') {

                $.ajax({

                    url: "<?php echo base_url(); ?>index.php/dropdownController/fetchcity",

                    method: "POST",

                    data: { state_id: state_id },

                    success: function (data) {

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

                    }

                });

            }

            else {

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

            }

        });

    });

</script>

Note: At the last of the file I wrote one jQuery code that will execute when your document loaded. I am using jQuery in code so you must have to load jquery.min.js file on the head portion in the file. Like

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

Hope you like the blog. PLease comment to ask questions..!!

  • Gagani Senarathne Hi.. I'm doing a project using php PDO (OOP) and html. But I have a section to add details from dependent dropdown. I tried it using ajax. The dependent part works. But the adding part doesn't work.. It wold be great if you could help me. Thanks.
    on 02 May, 2019 at 9:05pm