22-Apr-2022
.
Admin
Hi Guys,
Today, dynamic dependent dropdown in Codeigniter 4 with ajax is our main topic. you will learn Codeigniter dynamic dependent select box using ajax. In this article, we will implement a Codeigniter 4 dynamic dropdown from the database. this example will help you dynamic dependent dropdown in the Codeigniter example.
This example will help you dynamic dependent dropdown in Codeigniter example will guide you step by step on how to make a dependent dropdown list in CodeIgniter 4 using ajax and bootstrap 4.
Step 1: Install Codeigniter 4
This is optional; however, if you have not created the codeigniter app, then you maygo ahead and execute the below command:
composer create-project codeigniter4/appstarter ci-news
After Download successfully, extract clean new Codeigniter 4 application.
Step 2 : Basic Configurations
So in this step we will now set basic configuration on the app/config/app.php file, so let’s implement to application/config/config.php and open this file on text editor.
app/config/app.php
public $baseURL = 'http://localhost:8080';
To
public $baseURL = 'http://localhost/example/';
Step 3 : Database Configurations
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 : Database Configurations
application/config/database.php
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
Now here we go visit app/Models/ and create here one model named MainModel.php. Then add the following code into your MainModel.php file:
<?php
namespace App\Models;
use CodeIgniter\Model;
class MainModel extends Model {
/**
* Write code on Method
*
* @return response()
*/
public function __construct() {
parent::__construct();
//$this->load->database();
$db = \Config\Database::connect();
}
/**
* Write code on Method
*
* @return response()
*/
public function getCity() {
$query = $this->db->query('select * from city');
return $query->getResult();
}
/**
* Write code on Method
*
* @return response()
*/
public function getCityDepartment($postData) {
$sql = 'select * from department where city ='.$postData['city'] ;
$query = $this->db->query($sql);
return $query->getResult();
}
/**
* Write code on Method
*
* @return response()
*/
public function getDepartmentUsers($postData) {
$sql = 'select * from user_depart where department ='.$postData['department'] ;
$query = $this->db->query($sql);
return $query->getResult();
}
}
Step 6 : Set Up Controller
Here in this step we will create new controller that manages the dynamic dependent dropdown, hence create a DependentDropdownController.php file and append the example code in..
app/Controllers/DependentDropdownController.php
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use App\Models\MainModel;
class DependentDropdownController extends Controller {
/**
* Write code on Method
*
* @return response()
*/
public function index() {
helper(['form', 'url']);
$this->MainModel = new MainModel();
$data['cities'] = $this->MainModel->getCity();
return view('dropdown-view', $data);
}
/**
* Write code on Method
*
* @return response()
*/
public function getCityDepartment() {
$this->MainModel = new MainModel();
$postData = array(
'city' => $this->request->getPost('city'),
);
$data = $this->MainModel->getCityDepartment($postData);
echo json_encode($data);
}
/**
* Write code on Method
*
* @return response()
*/
public function getDepartmentUsers() {
$this->MainModel = new MainModel();
$postData = array(
'department' => $this->request->getPost('department'),
);
$data = $this->MainModel->getDepartmentUsers($postData);
echo json_encode($data);
}
}
Step 7 : Set Up View
Head over to application/views/ folder, create a new dropdown-view file. Likewise, open and add the suggested code example in application/views/dropdown-view.php file:
application/views/dropdown-view.php
<!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 - Nicesnippets.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 - Nicesnippets.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({
url:'<?=base_url()?>index.php/User/getCityDepartment',
method: 'post',
data: {city: city},
dataType: 'json',
success: function(response){
$('#sel_user').find('option').not(':first').remove();
$('#sel_depart').find('option').not(':first').remove();
$.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({
url:'<?=base_url()?>index.php/User/getDepartmentUsers',
method: 'post',
data: {department: department},
dataType: 'json',
success: function(response){
$('#sel_user').find('option').not(':first').remove();
$.each(response,function(index,data){
$('#sel_user').append('<option value="'+data['id']+'">'+data['name']+'</option>');
});
}
});
});
});
</script>
</body>
</html>
Step 8 : Run Codeigniter App:
All the required steps have been done, now you have to type the given below command and hit enter to run the Codeigniter app:
php spark serve
Now, Go to your web browser, type the given URL and view the app output:
http://localhost/demo/public/index.php/dropdown
I hope it can help you...
#Codeigniter 4