CodeIgniter 4 Dynamic Dependent Dropdown using jQuery Ajax

Share this Article
Reading Time: 7 minutes
6,851 Views

Inside this article we will see the concept of CodeIgniter 4 Dynamic Dependent Dropdown Using jQuery Ajax. We will have dropdowns which is connected with the previous selected value.

For example – Country (Dropdown) >> State (Dropdown) >> City (Dropdown)

This tutorial will help you to understand to handle dynamic dependent dropdowns using jquery ajax in CodeIgniter 4. Also it will be super easy to implement in your code as well.

Learn More –

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.


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.

 
#--------------------------------------------------------------------
# DATABASE
#--------------------------------------------------------------------

database.default.hostname = localhost
database.default.database = codeigniter4_app
database.default.username = root
database.default.password = root
database.default.DBDriver = MySQLi
database.default.DBPrefix =
   

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 at /app/Controllers folder.

Open DropdownController.php 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);
    }
}

Create Layout File

Go to /app/Views folder and create a file with name dropdown.php

Open dropdown.php 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

We hope this article helped you to CodeIgniter 4 Dynamic Dependent Dropdown Using jQuery Ajax in a very detailed way.

Buy Me a Coffee

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.

Was this post helpful?

PHP Web Development Courses on Offer in just $4
PHP Web Development Courses on Offer in just $4