Code your dreams into reality.
Every line of code is a step towards a better future.
Embrace the bugs, they make you a better debugger.

Country State City Dependent Dropdown using Ajax in Codeigniter 4

Last Updated on July 29, 2024 by

In this tutorial, i will create country state city dependent dropdown features in CodeIgniter 4 applications using jQuery ajax.

Here are steps to country state city dependent dropdown using ajax:

Step 1: Setting Up CodeIgniter 4

Download CodeIgniter 4 from the official website:https://codeigniter.com/user_guide/installation/index.html., and extract download zip file in xampp/htdocs directory.

Edit .env file, and set the database connection:

database.default.hostname = localhost
database.default.database = your_database_name
database.default.username = your_username
database.default.password = your_password
database.default.DBDriver = MySQLi

Step 2: Create Country State City Table

Run the following sql queries to create tables: countries, states, and cities:

CREATE TABLE countries (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL
);

CREATE TABLE states (
    id INT AUTO_INCREMENT PRIMARY KEY,
    country_id INT NOT NULL,
    name VARCHAR(100) NOT NULL,
    FOREIGN KEY (country_id) REFERENCES countries(id)
);

CREATE TABLE cities (
    id INT AUTO_INCREMENT PRIMARY KEY,
    state_id INT NOT NULL,
    name VARCHAR(100) NOT NULL,
    FOREIGN KEY (state_id) REFERENCES states(id)
);

Use the following insert query to insert some data in db tables:

INSERT INTO countries (name) VALUES ('USA'), ('Canada'), ('India');

INSERT INTO states (country_id, name) VALUES 
(1, 'California'), (1, 'Texas'), (1, 'New York'),
(2, 'Ontario'), (2, 'Quebec'), (2, 'British Columbia'),
(3, 'Maharashtra'), (3, 'Gujarat'), (3, 'Rajasthan');

INSERT INTO cities (state_id, name) VALUES 
(1, 'Los Angeles'), (1, 'San Francisco'), (1, 'San Diego'),
(2, 'Houston'), (2, 'Dallas'), (2, 'Austin'),
(3, 'New York City'), (3, 'Buffalo'), (3, 'Rochester'),
(4, 'Toronto'), (4, 'Ottawa'), (4, 'Mississauga'),
(5, 'Montreal'), (5, 'Quebec City'), (5, 'Laval'),
(6, 'Vancouver'), (6, 'Victoria'), (6, 'Surrey'),
(7, 'Mumbai'), (7, 'Pune'), (7, 'Nagpur'),
(8, 'Ahmedabad'), (8, 'Surat'), (8, 'Vadodara'),
(9, 'Jaipur'), (9, 'Udaipur'), (9, 'Jodhpur');

Step 3: Create Models

Go to app/models directory, and create country state city model file:

CountryModel.php

<?php

namespace App\Models;

use CodeIgniter\Model;

class CountryModel extends Model
{
    protected $table = 'countries';
    protected $primaryKey = 'id';
    protected $allowedFields = ['name'];
}

StateModel.php

<?php

namespace App\Models;

use CodeIgniter\Model;

class StateModel extends Model
{
    protected $table = 'states';
    protected $primaryKey = 'id';
    protected $allowedFields = ['country_id', 'name'];
}

CityModel.php

<?php

namespace App\Models;

use CodeIgniter\Model;

class CityModel extends Model
{
    protected $table = 'cities';
    protected $primaryKey = 'id';
    protected $allowedFields = ['state_id', 'name'];
}

Step 4: Create Controller

Create a controller file named LocationController.php in app/controllers directory that handle bussiness logic in it.

Now create some methods in controller file that handle fetch and display data from database based on dropdown selection using ajax:

<?php

namespace App\Controllers;

use App\Models\CountryModel;
use App\Models\StateModel;
use App\Models\CityModel;
use CodeIgniter\Controller;

class LocationController extends Controller
{
    public function index()
    {
        $countryModel = new CountryModel();
        $data['countries'] = $countryModel->findAll();
        return view('location_view', $data);
    }

    public function fetchStates()
    {
        $stateModel = new StateModel();
        $countryId = $this->request->getPost('country_id');
        $states = $stateModel->where('country_id', $countryId)->findAll();
        echo json_encode($states);
    }

    public function fetchCities()
    {
        $cityModel = new CityModel();
        $stateId = $this->request->getPost('state_id');
        $cities = $cityModel->where('state_id', $stateId)->findAll();
        echo json_encode($cities);
    }
}

Step 5: Create Dropdown View

In the app/Views/ directory create a new file location_view.php to show dependent dropdown in it:

<!DOCTYPE html>
<html>
<head>
    <title>Dynamic Dependent Dropdown in CodeIgniter 4 - itcodstuff.com</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <h1>Dynamic Dependent Dropdown in CodeIgniter 4 - itcodstuff.com</h1>
    <form>
        <label for="country">Country:</label>
        <select id="country" name="country">
            <option value="">Select Country</option>
            <?php foreach ($countries as $country): ?>
                <option value="<?= $country['id']; ?>"><?= $country['name']; ?></option>
            <?php endforeach; ?>
        </select>
        
        <label for="state">State:</label>
        <select id="state" name="state">
            <option value="">Select State</option>
        </select>

        <label for="city">City:</label>
        <select id="city" name="city">
            <option value="">Select City</option>
        </select>
    </form>

</body>
</html>

Step 6: Use Ajax in View

Implement ajax code to fetch country state and city data based on selected dropdown:

    <script>
        $(document).ready(function() {
            $('#country').change(function() {
                var countryId = $(this).val();
                if (countryId != '') {
                    $.ajax({
                        url: "<?= site_url('locationcontroller/fetchstates'); ?>",
                        method: "POST",
                        data: {country_id: countryId},
                        dataType: "json",
                        success: function(data) {
                            $('#state').html('<option value="">Select State</option>');
                            $.each(data, function(key, value) {
                                $('#state').append('<option value="'+ value.id +'">'+ value.name +'</option>');
                            });
                            $('#city').html('<option value="">Select City</option>');
                        }
                    });
                } else {
                    $('#state').html('<option value="">Select State</option>');
                    $('#city').html('<option value="">Select City</option>');
                }
            });

            $('#state').change(function() {
                var stateId = $(this).val();
                if (stateId != '') {
                    $.ajax({
                        url: "<?= site_url('locationcontroller/fetchcities'); ?>",
                        method: "POST",
                        data: {state_id: stateId},
                        dataType: "json",
                        success: function(data) {
                            $('#city').html('<option value="">Select City</option>');
                            $.each(data, function(key, value) {
                                $('#city').append('<option value="'+ value.id +'">'+ value.name +'</option>');
                            });
                        }
                    });
                } else {
                    $('#city').html('<option value="">Select City</option>');
                }
            });
        });
    </script>

Step 7: Define Routes

Edit app/Config/Routes.php file and define routes in it:

$routes->get('/', 'LocationController::index');
$routes->post('locationcontroller/fetchstates', 'LocationController::fetchStates');
$routes->post('locationcontroller/fetchcities', 'LocationController::fetchCities');

Step 8: Test the Application

Type the url: http://localhost/your_project_name/public/ on browser and test this application

Leave a Comment