To dynamic auto-populate or get a dependent dropdown in Codeigniter 4 with jquery ajax; In this tutorial guide, you will learn how to make a dynamic dependent dropdown to get dynamically or auto-populate second dropdown list to be populated dynamically or automatically based on the selected option from the first dropdown list in Codeigniter 4 with jQuery Ajax and bootstrap.
Dynamic Dependent Dropdown using Ajax in Codeigniter 4
Let’s follow the following steps to create a dynamic dependent dropdown and dynamically populate a second dropdownlist from a first dropDown list using jquery ajax in codeigniter 4 projects:
- Step 1: Download Codeigniter Project
- Step 2: Basic Configurations
- Step 3: Create Database With Table
- Step 4: Setup Database Credentials
- Step 5: Create Model File
- Step 6: Create Controller
- Step 7: Create Views
- Step 8: Test App On Browser
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: Test App On Browser
Now, 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.
Recommended Codeigniter Posts
If you have any questions or thoughts to share, use the comment form below to reach us.