Dynamic dependent dropdowns offer a seamless user experience by dynamically populating dropdown options based on selections made in a preceding dropdown. In CodeIgniter 4, implementing dynamic dependent dropdowns using jQuery Ajax provides a responsive way to manage interdependent data selections.
In this tutorial, we’ll see the comprehensive process of creating dynamic dependent dropdowns in CodeIgniter 4 utilizing jQuery Ajax.
For example – Country (Dropdown) >> State (Dropdown) >> City (Dropdown)
Throughout this tutorial, we’ll cover the process of setting up the CodeIgniter environment, creating the necessary controller and views, implementing jQuery Ajax requests.
Read More: CodeIgniter 4 How To Read Parse JSON File Tutorial
Let’s get started.
CodeIgniter 4 Installation
To create a CodeIgniter 4 setup run this given command into your shell or terminal. Please make sure composer should be installed.
composer create-project codeigniter4/appstarter codeigniter-4
Assuming you have successfully installed application into your local system.
Environment (.env) Setup
When we install CodeIgniter 4, we will have env file at root. To use the environment variables means using variables at global scope we need to do env to .env
Either we can do via renaming file as simple as that. Also we can do by terminal command.
Open project in terminal
cp env .env
Above command will create a copy of env file to .env file. Now we are ready to use environment variables.
Enable Development Mode
CodeIgniter starts up in production mode by default. You need to make it in development mode to see any error if you are working with application.
Open .env file from root.
# CI_ENVIRONMENT = production
// Do it to
CI_ENVIRONMENT = development
Now application is in development mode.
Create Database
To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.
We will use MySQL command to create database. Run this command into Sql tab of PhpMyAdmin.
CREATE DATABASE codeigniter4_app;
Successfully, we have created a database.
Create Database Tables
Next, we need to create tables. That table will be responsible to store data.
Let’s create tables with some columns.
“countries” table
CREATE TABLE countries (
id int(10) unsigned NOT NULL AUTO_INCREMENT,
name varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
sortname varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
phonecode varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
“states” table
CREATE TABLE states (
id int(10) unsigned NOT NULL AUTO_INCREMENT,
name varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
country_id int(11) NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
“cities” table
CREATE TABLE cities (
id int(10) unsigned NOT NULL AUTO_INCREMENT,
name varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
state_id int(11) NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
Successfully, we have created tables.
Read More: CodeIgniter 4 How To Send Email with Attachments Tutorial
Database Connection
Open .env file from project root.
Search for DATABASE. You should see the connection environment variables into it. Put your updated details of database connection string values.
#-------------------------------------------------------------------- # DATABASE #-------------------------------------------------------------------- database.default.hostname = localhost database.default.database = codeigniter4_app database.default.username = admin database.default.password = admin database.default.DBDriver = MySQLi database.default.DBPrefix = database.default.port = 3306
Now, database successfully connected with the application.
Dummy Data for Application
Here, you need to copy mysql query from this given file and run into sql tab of phpmyadmin. First download it and run.
You will see something like this after this test data insertion.
“countries” table
“states” table
“cities” table
Create Controller
Next, we need to create a controller file
php spark make:controller Dropdown --suffix
It will create a file DropdownController.php inside /app/Controllers folder.
Open file and write this complete code into it.
<?php namespace App\Controllers; use App\Controllers\BaseController; class DropdownController extends BaseController { private $db; public function __construct() { $this->db = db_connect(); } public function index() { $countries = $this->db->query("SELECT id, name from countries")->getResultArray(); return view("dropdown", compact('countries')); } public function getState() { $country_id = $this->request->getVar("country_id"); $states = $this->db->query("SELECT id, name from states where country_id = ".$country_id)->getResultArray(); return json_encode($states); } public function getCity() { $state_id = $this->request->getVar("state_id"); $cities = $this->db->query("SELECT id, name from cities where state_id = ".$state_id)->getResultArray(); return json_encode($cities); } }
Read More: CodeIgniter 4 How To Read XML Data to JSON Tutorial
Create Layout File
Go to /app/Views folder and create a file with name dropdown.php
Open file and write this complete code into it.
<!DOCTYPE html> <html lang="en"> <head> <title>CodeIgniter 4 Dynamic Dependent Dropdown using jQuery Ajax</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/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"> <h3>CodeIgniter 4 Dynamic Dependent Dropdown using jQuery Ajax</h3> <div class="panel panel-primary"> <div class="panel-heading">CodeIgniter 4 Dynamic Dependent Dropdown using jQuery Ajax</div> <div class="panel-body"> <div class="form-group"> <label for="country">Country:</label> <select id="country" name="country" class="form-control"> <option value="" selected disabled>Select Country</option> <?php foreach($countries as $key => $country){ ?> <option value="<?= $country['id'] ?>"> <?= $country['name'] ?></option> <?php } ?> </select> </div> <div class="form-group"> <label for="state">State:</label> <select name="state" id="state" class="form-control"></select> </div> <div class="form-group"> <label for="city">City:</label> <select name="city" id="city" class="form-control"></select> </div> </div> </div> </div> <script type=text/javascript> // when country dropdown changes $('#country').change(function() { var countryID = $(this).val(); if (countryID) { $.ajax({ type: "GET", url: "<?= base_url('getState')?>", data:{ country_id: countryID }, success: function(res) { var data = JSON.parse(res); if (res) { $("#state").empty(); $("#state").append('<option>Select State</option>'); $.each(data, function(key, value) { $("#state").append('<option value="' + value.id + '">' + value.name + '</option>'); }); } else { $("#state").empty(); } } }); } else { $("#state").empty(); $("#city").empty(); } }); // when state dropdown changes $('#state').on('change', function() { var stateID = $(this).val(); if (stateID) { $.ajax({ type: "GET", url: "<?= base_url('getCity')?>", data:{ state_id: stateID }, success: function(res) { var data = JSON.parse(res); if (res) { $("#city").empty(); $("#city").append('<option>Select City</option>'); $.each(data, function(key, value) { $("#city").append('<option value="' + value.id + '">' + value.name + '</option>'); }); } else { $("#city").empty(); } } }); } else { $("#city").empty(); } }); </script> </body> </html>
Create Route
Open Routes.php from /app/Config folder and add these routes into it.
//... $routes->get('dropdown','DropdownController::index'); $routes->get('getState','DropdownController::getState'); $routes->get('getCity','DropdownController::getCity'); //...
Application Testing
Open project terminal and start development server via command:
php spark serve
URL: http://localhost:8080/dropdown
That’s it.
We hope this article helped you to learn about CodeIgniter 4 Dynamic Dependent Dropdown Using jQuery Ajax in a very detailed way.
Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.
If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.