Codeigniter 4 Dynamic Dependent Dropdown with Ajax

Dynamic dependent dropdown in Codeigniter 4 with Ajax. In this example, you will learn how to implement dynamic dependent dropdown in Codeigniter 4 with Ajax and bootstrap 4.

This Codeigniter 4 ajax dependent dropdown example will guide you step by step on how to make dependent dropdown list in codeigniter 4 using ajax and bootstrap 4.

Dynamic dependent dropdown in Codeigniter 4 with Ajax

  • Download Codeigniter Latest
  • Basic Configurations
  • Create Database With Table
  • Setup Database Credentials
  • Create Model File
  • Create Controller
  • Create Views
  • Start Development server

Step 1: Download Codeigniter Project

In this step, you will download the latest version of Codeigniter 4, Go to this link https://codeigniter.com/download Download Codeigniter 4 fresh new setup and unzip the setup in your local system xampp/htdocs/ . And change the download folder name “demo”

Step 2: Basic Configurations

Next, you will set 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 With Table

In this step, you need to create a database name demo, so let’s open your PHPMyAdmin and create the database with the name demo. After successfully create a database, you can use the below SQL query for creating a table in your database.

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(3) 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

In this step, you need to connect our project to the database. you need to go app/Config/Database.php and open database.php file in text editor. After opening the file in a text editor, you need to set up database credentials in this file like below.

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

Step 5: Create Model File

In this step, visit app/Models/ and create here one model named Main_model.php. Then add the following code into your Main_model.php file:

<?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(); } } 

Step 6: Create Controller

In this step, Visit app/Controllers and create a controller name Dropdown.php. In this controller, you need to add the following methods into it:

<?php namespace App\Controllers; use CodeIgniter\Controller;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use App\Models\Main_model; class Dropdown extends Controller { public function index() { helper(['form', 'url']); $this->Main_model = new Main_model(); $data['cities'] = $this->Main_model->getCity(); return view('dropdown-view', $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 7: Create Views

In this step, you need to create one view files name dropdown-view.php and update the following code into your 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 Ajax Dependent Dropdown List - Tutsmake.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 - Tutsmake.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()?>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>

Step 8: Start Development server

For start development server, Go to the browser and hit below the URL.

http://localhost/demo/public/index.php/dropdown

Conclusion

In this Codeigniter 4 ajax dynamic dropdown example. In this tutorial you have successfully created Dynamic dependent dropdown in Codeigniter 4 with Ajax.

Recommende CodeIgniter 4 Tutorial

  1. Install / Download Codeigniter 4 By Manual, Composer, Git
  2. Codeigniter 4 Remove Public and Index.php From URL
  3. Codeigniter 4 Application Folder / Directory Structure
  4. Create Controller, Model, View Example Codeigniter 4

If you have any questions or thoughts to share, use the comment form below to reach us.

Related Posts