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.

CodeIgniter 4 Ajax Dynamic Dependent Dropdown Tutorial

Last Updated on July 28, 2024 by

Ajax allows developers to create features in CodeIgniter 4 applications to fetch and populate data from a database based on a dropdown selection using AJAX.

Let’s start to implementing a dynamic category and subcategory 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 Category and Subcategory Table

Run the following sql queries to create two tables: categories and subcategories:


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

CREATE TABLE subcategories (
    id INT AUTO_INCREMENT PRIMARY KEY,
    category_id INT NOT NULL,
    name VARCHAR(100) NOT NULL,
    FOREIGN KEY (category_id) REFERENCES categories(id)
);

INSERT INTO categories (name) VALUES ('Electronics'), ('Books'), ('Clothing');

INSERT INTO subcategories (category_id, name) VALUES 
(1, 'Mobile Phones'), (1, 'Laptops'), (1, 'Televisions'),
(2, 'Fiction'), (2, 'Non-fiction'), (2, 'Science Fiction'),
(3, 'Men'), (3, 'Women'), (3, 'Kids');

Step 3: Create Models

Go to app/models directory, and create category and subcategory model file:

CategoryModel.php

<?php

namespace App\Models;

use CodeIgniter\Model;

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

SubcategoryModel.php

<?php

namespace App\Models;

use CodeIgniter\Model;

class SubcategoryModel extends Model
{
    protected $table = 'subcategories';
    protected $primaryKey = 'id';
    protected $allowedFields = ['category_id', 'name'];
}

Step 4: Create Controller

Create a new file named DropdownController.php in app/Controllers/ directory, and implement ajax methods in it to pass dropdown data from to view:

<?php

namespace App\Controllers;

use App\Models\CategoryModel;
use App\Models\SubcategoryModel;
use CodeIgniter\Controller;

class DropdownController extends Controller
{
    public function index()
    {
        $categoryModel = new CategoryModel();
        $data['categories'] = $categoryModel->findAll();
        return view('dropdown_view', $data);
    }

    public function fetchSubcategories()
    {
        $subcategoryModel = new SubcategoryModel();
        $categoryId = $this->request->getPost('category_id');
        $subcategories = $subcategoryModel->where('category_id', $categoryId)->findAll();
        echo json_encode($subcategories);
    }
}

Step 5: Create View

In the app/Views/ directory create a new file dropdown_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</h1>
    <form>
        <label for="category">Category:</label>
        <select id="category" name="category">
            <option value="">Select Category</option>
            <?php foreach ($categories as $category): ?>
                <option value="<?= $category['id']; ?>"><?= $category['name']; ?></option>
            <?php endforeach; ?>
        </select>
        
        <label for="subcategory">Subcategory:</label>
        <select id="subcategory" name="subcategory">
            <option value="">Select Subcategory</option>
        </select>
    </form>


</body>
</html>

Step 6: Use Ajax in View

Implement ajax code to fetch and display data on dependent dropdown:

    <script>
        $(document).ready(function() {
            $('#category').change(function() {
                var categoryId = $(this).val();
                if (categoryId != '') {
                    $.ajax({
                        url: "<?= site_url('dropdowncontroller/fetchsubcategories'); ?>",
                        method: "POST",
                        data: {category_id: categoryId},
                        dataType: "json",
                        success: function(data) {
                            $('#subcategory').html('<option value="">Select Subcategory</option>');
                            $.each(data, function(key, value) {
                                $('#subcategory').append('<option value="'+ value.id +'">'+ value.name +'</option>');
                            });
                        }
                    });
                } else {
                    $('#subcategory').html('<option value="">Select Subcategory</option>');
                }
            });
        });
    </script>

Step 7: Test the Application

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

Leave a Comment