Codeigniter 4 Dependent Dropdown using jQuery Ajax Example

Dependent dropdown in codeigniter 4 using jQuery ajax; In this example tutorial i will guide you step by step on how to implement dependent dropdown using jQuery and ajax in PHP Codeigniter 4 app with populate dynamic data.

For build dynamic dependent dropdown in codeigniter 4 app, you have to use Ajax jQuery with Codeigniter 4 framework. So in this example, you have to build dynamic dependent dropdown in Codeigniter 4 using Ajax jQuery. In this example; you can find step by step guide for build how to create dynamic dependent dropdown in PHP Codeigniter 4 using Ajax with jQuery, Mysql and Bootstrap 4 library.

Fort this Dependent dropdown in PHP codeigniter 4 using jQuery ajax; In this example, the dependent dropdown will make. In that the first city would be dropdown. When the visitor selects the city, Then the list of department will be populated in the next dropdown. And when the department will select the department from dropdown. Then the list of users will be populated in the next dropdown .

Dependent Dropdown in PHP Codeigniter 4 Example

  • Install Codeigniter 4 Application
  • Basic App Configurations
  • Create Database and Table
  • Setup Database Credentials
  • Create Controller
  • Create Views
  • Setup Routes
  • Start Development server

Step 1 – Install Codeigniter 4 Application

First of all, you need to ownload the latest version of Codeigniter 4. So, visit this link https://codeigniter.com/download Download Codeigniter 4 app and unzip the setup in your local system xampp/htdocs/ .

Note that, please change the download folder name “demo”.

Step 2 – Basic App Configurations

Now, you need to some basic configuration on the app/config/app.php file, so let’s go to application/config/config.php and open this file on text editor.

Set Base URL like this

public $baseURL = 'http://localhost:8080';
To
public $baseURL = 'http://localhost/demo/';

Step 3 – Create Database and Table

Create a database and table by executing the following SQL query:

CREATE DATABASE demo;

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

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

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;

Step 4 – Setup Database Credentials

To connect your codeigniter 4 app to the database. So, visit app/Config/ directory and open Database.php. Then add the databasae details like below into database.php file:

public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'test',
        'password' => '4Mu99BhzK8dr4vF1',
        'database' => 'demo',
        'DBDriver' => 'MySQLi',
        'DBPrefix' => '',
        'pConnect' => false,
        'DBDebug'  => (ENVIRONMENT !== 'development'),
        'cacheOn'  => false,
        'cacheDir' => '',
        'charset'  => 'utf8',
        'DBCollat' => 'utf8_general_ci',
        'swapPre'  => '',
        'encrypt'  => false,
        'compress' => false,
        'strictOn' => false,
        'failover' => [],
        'port'     => 3306,
	];

Step 5 – Create Model and Controller

Create Main_model.php file. So, visit app/Modelsdirectory and create Main_model.php.Then add the following code into it:

<?php

namespace App\Models;

use CodeIgniter\Model;

class Main_model extends Model {

    
    public function __construct() {
        parent::__construct();
        //$this->load->database();
        $db = \Config\Database::connect();
    }

    public function getCity() {

       $query = $this->db->query('select * from city');
       return $query->getResult();
    }

    public function getCityDepartment($postData) {
      $sql = 'select * from department where city ='.$postData['city'] ;
      $query =  $this->db->query($sql);
      
      return $query->getResult();
    }    

    public function getDepartmentUsers($postData) {
      $sql = 'select * from user_depart where department ='.$postData['department'] ;
      $query =  $this->db->query($sql);
      
      return $query->getResult();
    }


}

Create DropdownController.php file. So, visit app/Controllers directory and create DropdownController.php.Then add the following code into it:

<?php

namespace App\Controllers;

use CodeIgniter\Controller;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use App\Models\Main_model;

class DropdownController extends Controller {


    public function index() {
        
        helper(['form', 'url']);
        $this->Main_model = new Main_model();
        $data['cities'] = $this->Main_model->getCity();
        return view('dropdown-list', $data);
    }

    public function getCityDepartment() {

        $this->Main_model = new Main_model();

        $postData = array(
            'city' => $this->request->getPost('city'),
        );

        $data = $this->Main_model->getCityDepartment($postData);

        echo json_encode($data);
    }    

    public function getDepartmentUsers() {

        $this->Main_model = new Main_model();

        $postData = array(
            'department' => $this->request->getPost('department'),
        );

        $data = $this->Main_model->getDepartmentUsers($postData);

        echo json_encode($data);
    }


}

Step 6 – Create Views

Create dropdown-list.php view file, so visit application/views/ directory and create dropdown-list.php file. Then add the following HTML into dropdown-list.php file:

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="csrf-token" content="content">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="csrf-token" content="{{ csrf_token() }}">

        <title>Codeigniter 4 Dependent Dropdown using Ajax - Laratutorials.com</title>


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

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

    </head>
<body>
    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">
                        <h2 class="text-success">Codeigniter 4 Dynamic Dependent Dropdown with Ajax - laratutorials.COM</h2>
                    </div>
                    <div class="card-body">
                     <form>
                        <div class="form-group">
                          <label for="country">City</label>
                          <select class="form-control" id="sel_city">
                          <option value="">Select City</option>

                           <?php foreach($cities as $city){?>
                              <option value="<?php echo $city->id;?>"><?php echo $city->cityname;?></option>"
                           <?php }?>
                            
                          </select>
                        </div>
                        <div class="form-group">
                          <label for="state">Departments</label>
                          <select class="form-control" id="sel_depart">
                            
                          </select>
                        </div>                        

                        <div class="form-group">
                          <label for="city">Users</label>
                          <select class="form-control" id="sel_user">
                            
                          </select>
                        </div>
                    </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
  <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()?>/DropdownController/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()?>/DropdownController/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>

Step 7 – Setup Routes

To define a route, So, visit app/Config/ directory and open Routes.php file. Then add the following routes into it:

$routes->setDefaultController('DropdownController');
$routes->get('/', 'DropdownController::index');

Step 8 – Start Development server

Execute the following command into command prompt or terminal to start the codeigniter 4 application:

php spark serve

Then visit your web browser and hit the following url on it:

http://localhost/demo/

OR

http://localhost:8080/

Conclusion

CodeIgniter 4 dynamic dependent dropdown tutorial. In this example,you have learned how to implement dependent dropdown using jQuery and ajax in PHP Codeigniter 4 app with populate dynamic data.

Recommended CodeIgniter 4 Tutorial

  1. Codeigniter 4 Ajax Form Submit Validation Example
  2. Codeigniter 4 File Upload Validation Example
  3. Codeigniter 4 Image Upload Preview Using jQuery Example
  4. Codeigniter 4 Ajax Image Upload Preview Example
  5. How to Upload Multiple Images in Codeigniter 4
  6. Codeigniter 4 Multiple Image Upload with Preview
  7. Codeigniter 4 Pagination Example; Create Pagination in Codeigniter
  8. Codeigniter 4 CRUD with Datatables Example
  9. CodeIgniter 4 Server Side DataTable Example
  10. Create Rest Api In Codeigniter 4 App
  11. Codeigniter 4 Image Crop and Save using Croppie Example

Leave a Comment