Country State City Dependent Dropdown in Codeigniter 4

This tutorial will show you how to make a dropdown menu for countries, states, and cities that depends on each other using PHP Codeigniter 4 and Ajax. It’s a simple process that involves using Ajax, jQuery, Bootstrap, and MySQL database. By following this guide, you will be able to create a dropdown menu that dynamically updates based on user input.

Codeigniter 4 Country State City Dropdown Using Ajax Example

Here are the steps to implement dynamic country state city dependent dropdown using Ajax in Codeigniter 4 apps:

  • Download Codeigniter Latest
  • Basic Configurations
  • Create Database With Table
  • Setup Database Credentials
  • Create Model File
  • Create Controller
  • Create Views
  • Test App On Browser

Download Codeigniter Latest

In this step, you will need to download the latest version of CodeIgniter 4 from the official website by following the link: https://codeigniter.com/download

After downloading the setup, unzip the downloaded file to your local system’s xampp/htdocs/ directory. You can choose any directory you prefer, but for the sake of simplicity, let’s assume that you have unzipped the file in the xampp/htdocs/ directory.

Now, rename the unzipped folder to “demo”. This will be the name of your CodeIgniter 4 application directory.

Step 2: Basic Configurations

Here are the steps to set the base URL in CodeIgniter 4:

  1. Open the “app/config/app.php” file in your CodeIgniter 4 application using a text editor.
  2. Locate the “baseURL” parameter in the file.
  3. Uncomment the “baseURL” parameter by removing the ‘#’ character at the beginning of the line.
  4. Set the value of the “baseURL” parameter to the base URL of your CodeIgniter 4 application.

Here is an example of how to set the base URL:

public $baseURL = 'http://localhost:8080';
To
public $baseURL = 'http://localhost/demo/';

Make sure to replace “demo” with the name of your CodeIgniter 4 application directory.

After setting the base URL, save the “app/config/app.php” file. This will configure the base URL for your CodeIgniter 4 application.

Step 3: Create Database With Table

Here are the steps to create a database and a table in PHPMyAdmin:

  1. Open PHPMyAdmin in your web browser.
  2. Click on the “Databases” tab in the top navigation bar.
  3. Enter a name for your new database in the “Create database” field, such as “demo”.
  4. Click the “Create” button to create the new database.

Once you have created the new database, you can use the following SQL query to create a table for storing country, state, and city data:

CREATE DATABASE demo;
 
CREATE TABLE `countries` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
 `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active | 0=Inactive',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
 
CREATE TABLE `states` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `country_id` int(11) NOT NULL,
 `name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
 `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active | 0=Inactive',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
 
CREATE TABLE `cities` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `state_id` int(11) NOT NULL,
 `name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
 `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active | 0=Inactive',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
 
INSERT INTO `countries` VALUES (1, 'USA', 1);
INSERT INTO `countries` VALUES (2, 'Canada', 1);
  
  
INSERT INTO `states` VALUES (1, 1, 'New York', 1);
INSERT INTO `states` VALUES (2, 1, 'Los Angeles', 1);
INSERT INTO `states` VALUES (3, 2, 'British Columbia', 1);
INSERT INTO `states` VALUES (4, 2, 'Torentu', 1);
  
  
INSERT INTO `cities` VALUES (1, 2, 'Los Angales', 1);
INSERT INTO `cities` VALUES (2, 1, 'New York', 1);
INSERT INTO `cities` VALUES (3, 4, 'Toranto', 1);
INSERT INTO `cities` VALUES (4, 3, 'Vancovour', 1);

This SQL query creates a table named “location” with four columns: “id”, “country”, “state”, and “city”. The “id” column is an auto-incrementing integer that serves as the primary key for the table. The “country”, “state”, and “city” columns are all of type varchar(255) and are used to store the names of countries, states, and cities, respectively.

After executing this SQL query, you will have a table in your “demo” database that you can use to store country, state, and city data.

Step 4: Setup Database Credentials

Here is the simplified version of the content:

Now we need to connect our project to the database. To do this, follow these steps:

  1. Go to the “app/Config” directory in your CodeIgniter 4 project.
  2. Open the “Database.php” file in a text editor.
  3. Set up your database credentials in this file.

Here’s an example of how to set up your database credentials:

public $default = [
	'DSN'      => '',
	'hostname' => 'localhost',
	'username' => 'root',
	'password' => '',
	'database' => 'demo',
	'DBDriver' => 'MySQLi',
	'DBPrefix' => '',
	'pConnect' => false,
	'db_debug' => (ENVIRONMENT !== 'production'),
	'cache_on' => false,
	'cache_dir' => '',
	'charset' => 'utf8',
	'dbcollat' => 'utf8_general_ci',
	'swap_pre' => '',
	'encrypt' => false,
	'compress' => false,
	'strict_on' => false,
	'failover' => [],
	'save_queries' => true
];

After setting up your database credentials, save the “Database.php” file. This will configure the database connection for your CodeIgniter 4 project.

Step 5: Create Model File

Now, we need to create a new model in our CodeIgniter 4 project to interact with our database. To do this, follow these steps:

  1. Go to the “app/Models” directory in your CodeIgniter 4 project.
  2. Create a new PHP file in this directory and name it “Main_model.php”.
  3. Open the “Main_model.php” file in a text editor.
  4. Add the following code to the file:
<?php
namespace App\Models;
 
use CodeIgniter\Database\ConnectionInterface;
use CodeIgniter\Model;
  
class Main_model extends Model
{
  
      
    public function __construct() {
        parent::__construct();
        //$this->load->database();
        $db = \Config\Database::connect();
    }
  
    public function getCountries()
    {
        $this->db->from('countries');
        $query=$this->db->get();
        return $query->result();
    }
      
  
    public function getStates($postData)
    {
        $this->db->from('states');
        $this->db->where('country_id',$postData['country_id']);
        $query=$this->db->get();
        return $query->result();
    } 
 
    public function getCities($postData)
    {
        $this->db->from('cities');
        $this->db->where('state_id',$postData['state_id']);
        $query=$this->db->get();
        return $query->result();
    }
 
  
}

Step 6: Create Controller

Next step, Goto app/Controllers and create a controller with the name DropdownAjaxController.php. In this controller we need to add the following methods into it to perform dynamic dependant dropdown for the country , state and city

<?php
  
namespace App\Controllers;
  
use CodeIgniter\Controller;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use App\Models\Main_model;
  
class DropdownAjaxController extends Controller {
  
  
    public function index() {
          
        helper(['form', 'url']);
        $this->Main_model = new Main_model();
        $data['countries'] = $this->Main_model->getCountries();
        return view('dropdown-view', $data);
    }
 
    public function getStates() {
  
        $this->Main_model = new Main_model();
  
        $postData = array(
            'country_id' => $this->request->getPost('country_id'),
        );
  
        $data = $this->Main_model->getStates($postData);
  
        echo json_encode($data);
    }
  
    public function getCities() {
  
        $this->Main_model = new Main_model();
  
        $postData = array(
            'state_id' => $this->request->getPost('state_id'),
        );
  
        $data = $this->Main_model->getCities($postData);
  
        echo json_encode($data);
    }    
  
  
  
}

Step 7: Create Views

Next Step, We need to create view files with the name of dropdown-view.php and update the bellow written 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 Dependent Country State City Dropdown using Ajax - torqueprogramming.co.in</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 Dependent Country State City Dropdown using Ajax - tutsmake.com</h2>
                        </div>
                        <div class="card-body">
                            <form>
                                <div class="form-group">
                                    <label for="country">Countries</label>
                                    <select class="form-control" id="country_id">
                                        <option value="">Select Country</option>
                                        <?php foreach($countries as $c){?>
                                        <option value="<?php echo $c->id;?>"><?php echo $c->name;?></option>
                                        "
                                        <?php }?>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label for="state">States</label>
                                    <select class="form-control" id="state_id"> </select>
                                </div>
                                <div class="form-group">
                                    <label for="city">Cities</label>
                                    <select class="form-control" id="city_id"> </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
                $("#country_id").change(function () {
                    var country_id = $(this).val();
                    // AJAX request
                    $.ajax({
                        url: "<?=base_url()?>/DropdownAjaxController/getStates",
                        method: "post",
                        data: { country_id: country_id },
                        dataType: "json",
                        success: function (response) {
                            // Remove options
                            $("#state_id").find("option").not(":first").remove();
                            $("#city_id").find("option").not(":first").remove();
                            // Add options
                            $.each(response, function (index, data) {
                                $("#state_id").append('<option value="' + data["id"] + '">' + data["name"] + "</option>");
                            });
                        },
                    });
                });
                // Department change
                $("#state_id").change(function () {
                    var state_id = $(this).val();
                    // AJAX request
                    $.ajax({
                        url: "<?=base_url()?>/DropdownAjaxController/getCities",
                        method: "post",
                        data: { state_id: state_id },
                        dataType: "json",
                        success: function (response) {
                            // Remove options
                            $("#city_id").find("option").not(":first").remove();
                            // Add options
                            $.each(response, function (index, data) {
                                $("#city_id").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 example, we will implement a dynamic dependent country state city dropdown in CodeIgniter 4 using Ajax and Bootstrap 4. This will allow users to select their country, which will then populate a dropdown menu with the states or provinces for that country. After selecting a state or province, another dropdown menu will appear with the cities for that state or province.

By using Ajax and Bootstrap 4, we can create this dynamic dropdown menu without requiring the page to be refreshed. This provides a better user experience and makes our application more responsive.

Follow the steps outlined in this guide to create your own dynamic dependent country state city dropdown in CodeIgniter 4.

You May Also Like

Leave a Reply

Your email address will not be published. Required fields are marked *