Dynamic dependent dropdown in CodeIgniter 3 with AJAX

Dynamically dependent dropdown commonly seen in the country, state, and city selection on the webpage. The data on the child element changes according to the value of the parent element.

The process follows the same way if there are more than 2 dropdown elements.

To do this you can either use only PHP or jQuery AJAX.

In this tutorial, I am using jQuery AJAX to make dynamic dependent dropdown in CodeIgniter.

Dynamic dependent dropdown in CodeIgniter 3 with AJAX


Contents

  1. Table structure
  2. Configuration
  3. Model
  4. Controller
  5. View
  6. Demo
  7. Conclusion

1. Table structure

I am using three tables –

city

CREATE TABLE `city` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `cityname` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

department

CREATE TABLE `department` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `depart_name` varchar(80) NOT NULL,
  `city` int(3) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

user_depart

CREATE TABLE `user_depart` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `username` varchar(80) NOT NULL,
  `name` varchar(80) NOT NULL,
  `email` varchar(80) NOT NULL,
  `department` int(3) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

2. Configuration

Navigate to application/config/database.php and define Database connection.

$db['default'] = array(
 'dsn' => '',
 'hostname' => 'localhost',
 'username' => 'root', // Username
 'password' => '', // Password
 'database' => 'tutorial', // Database name
 'dbdriver' => 'mysqli',
 'dbprefix' => '',
 'pconnect' => FALSE,
 'db_debug' => (ENVIRONMENT !== 'production'),
 'cache_on' => FALSE,
 'cachedir' => '',
 'char_set' => 'utf8',
 'dbcollat' => 'utf8_general_ci',
 'swap_pre' => '',
 'encrypt' => FALSE,
 'compress' => FALSE,
 'stricton' => FALSE,
 'failover' => array(),
 'save_queries' => TRUE
);

Default controller

Open application/config/routes.php and edit default_controller value to User.

$route['default_controller'] = 'User';

Load Database

To access the MySQL database require loading database library.

Open application/config/autoload.php and add the database in libraries array().

$autoload['libraries'] = array("database");

3. Model

Create a new Main_model.php file in application/models/ directory.

Created 3 methods –

  • getCity() – Select records from city table and return it.
  • getCityDepartment() – Select records from department table according to the city.
  • getDepartmentUsers() – Select records from user_depart table according to the department.

Completed Code

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Main_model extends CI_Model {

  // Get cities
  function getCity(){

    $response = array();
 
    // Select record
    $this->db->select('*');
    $q = $this->db->get('city');
    $response = $q->result_array();

    return $response;
  }

  // Get City departments
  function getCityDepartment($postData){
    $response = array();
 
    // Select record
    $this->db->select('id,depart_name');
    $this->db->where('city', $postData['city']);
    $q = $this->db->get('department');
    $response = $q->result_array();

    return $response;
  }

  // Get Department user
  function getDepartmentUsers($postData){
    $response = array();
 
    // Select record
    $this->db->select('id,name,email');
    $this->db->where('department', $postData['department']);
    $q = $this->db->get('user_depart');
    $response = $q->result_array();

    return $response;
  }

}

4. Controller

Create a new User.php file in application/controllers/ directory.

Created 3 methods –

  • index() – Get cities array list from Main_model and pass it as data in $this->view->data('user_view',$data).
  • getCityDepartment() – Handle AJAX request when city is been selected from the <select> element. Get department list according to the POST city value and return it.
  • getDepartmentUsers() – This method also use to handle AJAX request. Select users list according to the POST department value and return it.

Completed Code

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class User extends CI_Controller {

  public function index(){
    // load base_url 
    $this->load->helper('url');
   
    //load model 
    $this->load->model('Main_model');
   
    // get cities 
    $data['cities'] = $this->Main_model->getCity();
   
    // load view 
    $this->load->view('user_view',$data); 
  }

  public function getCityDepartment(){ 
    // POST data 
    $postData = $this->input->post();
    
    // load model 
    $this->load->model('Main_model');
    
    // get data 
    $data = $this->Main_model->getCityDepartment($postData);
    echo json_encode($data); 
  }

  public function getDepartmentUsers(){ 
    // POST data 
    $postData = $this->input->post();

    // load model 
    $this->load->model('Main_model');
    
    // get data 
    $data = $this->Main_model->getDepartmentUsers($postData);
    echo json_encode($data); 
  }
}

5. View

Create a new user_view.php file in application/views/ directory.

Three <select> element created for city, department, and user selection. The city options are created by looping on the $cities array.

The other two <select> elements for department and user will be empty. They were auto-filled as per options selection with jQuery.

Defined change event in city and department <select> element.


jQuery –

City Change

When city dropdown option is been changed then send an AJAX request to index.php/User/getCityDepartment and pass city value as data.

On successful callback remove all options except first from the department and user dropdown.

Append response data on department element.

Department Change

When department dropdown option is been changed then send an AJAX request to index.php/User/getDepartmentUsers and pass department value as data.

On successful callback remove all options except first from the user dropdown.

Append response data on the user dropdown.

Completed Code

<!doctype html>
<html>
 <body>
 
   <table border='0'>

     <!-- City -->
     <tr>
       <td>City</td>
       <td>
         <select id='sel_city'>
           <option>-- Select city --</option>
           <?php
           foreach($cities as $city){
             echo "<option value='".$city['id']."'>".$city['cityname']."</option>";
           }
           ?>
        </select>
      </td>
    </tr>

    <!-- Department -->
    <tr>
      <td>Department</td>
      <td>
        <select id='sel_depart'>
          <option>-- Select deparment --</option>
        </select>
      </td>
    </tr>

    <!-- User -->
    <tr>
      <td>User</td>
      <td>
        <select id='sel_user'>
          <option>-- Select user --</option>
        </select>
      </td>
    </tr>
  </table>
 
  <!-- Script -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

  <script type='text/javascript'>
  // baseURL variable
  var baseURL= "<?php echo base_url();?>";
 
  $(document).ready(function(){
 
    // City change
    $('#sel_city').change(function(){
      var city = $(this).val();

      // AJAX request
      $.ajax({
        url:'<?=base_url()?>index.php/User/getCityDepartment',
        method: 'post',
        data: {city: city},
        dataType: 'json',
        success: function(response){

          // Remove options 
          $('#sel_user').find('option').not(':first').remove();
          $('#sel_depart').find('option').not(':first').remove();

          // Add options
          $.each(response,function(index,data){
             $('#sel_depart').append('<option value="'+data['id']+'">'+data['depart_name']+'</option>');
          });
        }
     });
   });
 
   // Department change
   $('#sel_depart').change(function(){
     var department = $(this).val();

     // AJAX request
     $.ajax({
       url:'<?=base_url()?>index.php/User/getDepartmentUsers',
       method: 'post',
       data: {department: department},
       dataType: 'json',
       success: function(response){
 
         // Remove options
         $('#sel_user').find('option').not(':first').remove();

         // Add options
         $.each(response,function(index,data){
           $('#sel_user').append('<option value="'+data['id']+'">'+data['name']+'</option>');
         });
       }
    });
  });
 
 });
 </script>
 </body>
</html>

6. Demo

View Demo


7. Conclusion

In this tutorial, I showed you how you can use AJAX to make dynamic dependent dropdown. Follow the same way if there is the other type of element e.g. textbox, textarea, etc. but you need to modify the script.

If you found this tutorial helpful then don't forget to share.