CodeIgniter 4 Dynamic Dependent Dropdown using jQuery Ajax

Share this Article
Reading Time: 7 minutes
766 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 –

Note*: For this article, CodeIgniter v4.1 setup has been installed. May be when you are seeing, version will be updated. CodeIgniter 4.x still is in development mode.

Let’s get started.


Download & Install CodeIgniter 4 Setup

We need to download & install CodeIgniter 4 application setup to system. To set application we have multiple options to proceed.

Here are the following ways to download and install CodeIgniter 4 –

  • Manual Download
  • Composer Installation
  • Clone Github repository of CodeIgniter 4

Complete introduction of CodeIgniter 4 basics – Click here to go. After going through this article you can easily download & install setup.

Here is the command to install via composer –

$ composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.


Turn Development Mode On

When we install CodeIgniter 4, we have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

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.

CodeIgniter starts up in production mode by default. Let’s do it in development mode. So that while working if we get any error then error will show up.

# CI_ENVIRONMENT = production

// Do it to 

CI_ENVIRONMENT = development

Now application is in development mode.


Create Database & Table in Application

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE codeigniter4_app;

Next, we need 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 a database and a table. Let’s connect with the application.


Database Connectivity to Application

Open .env file from project root. Search for DATABASE. You should see the connection environment variables.

Let’s set the value for those to connect with database.

 
#--------------------------------------------------------------------
# DATABASE
#-------------------------------------------------------------------- 
 database.default.hostname = localhost
 database.default.database = codeigniter4_app
 database.default.username = root
 database.default.password = root
 database.default.DBDriver = MySQLi
   

Now, database successfully connected with 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 route into it.

//...

$routes->get('dropdown','DropdownController::index');
$routes->get('getState','DropdownController::getState');
$routes->get('getCity','DropdownController::getCity');

//...

Application Testing

Start development server:

$ 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

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.

Find More on CodeIgniter 4 here