Want to learn coding through videos for free?
Check my youtube channel => HERE!

Dynamic Select Options Dependent Dropdown in Codeigniter and Ajax

Dynamic Select Options Dependent Dropdown in Codeigniter and Ajax

This is the ultimate tutorial about Select Options dependent using Codeigniter and JQuery Ajax.

If you want to know:

How to create dependent select options, insert, update, and delete with Codeigniter and Ajax.

Then you will like this tutorial.

However, if you are a beginner in Codeigniter I suggest you learn "Codeigniter Tutorial for Beginners" first.

Let’s dive right in.

Table of Content:

1. Preparation

2. Creating a Database and Table.

3. Installing and Configuring Codeigniter

4. Basic Dependent dropdown in Codeigniter and Ajax.

5. Insert with Select Option dependent in Codeigniter and Ajax.

6. Displays data that has been inserted into datatable.

7. Update with Select Option dependent in Codeigniter and Ajax.

8. Delete data to the database.

 

Step #1. Preparation

To create select options dependent in Codeigniter and AJAX Jquery, here's what you need to prepare:

1. Codeigniter

2. JQuery

3. Bootstrap (optional)

4. Datatable (optional)

Even though Bootstrap and Datatable are optional, I strongly recommend that you have all the lists above. 

Because I will use all the lists above in this tutorial.

 

Step #2. Creating a Database and Table

Create a database named “pos_db”. If you create a database with the same name it's better.

To create a database “pos_db” in MySQL, it can be done by executing the following query:

CREATE DATABASE pos_db;

Next is creating tables. In this tutorial, we need 3 tables, namely: category, sub_category, and product.

To create a "category" table can be done by executing the following query:

CREATE TABLE category(
category_id INT PRIMARY KEY AUTO_INCREMENT,
category_name VARCHAR(100)
)ENGINE=INNODB;

To create a "sub_category" table can be done by executing the following query:

CREATE TABLE sub_category(
subcategory_id INT PRIMARY KEY AUTO_INCREMENT,
subcategory_name VARCHAR(100),
subcategory_category_id INT
)ENGINE=INNODB;

To create a "product" table can be done by executing the following query:

CREATE TABLE product(
product_id INT PRIMARY KEY AUTO_INCREMENT,
product_name VARCHAR(100),
product_price INT,
product_category_id INT,
product_subcategory_id INT
)ENGINE=INNODB;

Next, insert some data into the "category" and "sub_category" tables.

Insert some data into the "category" table by executing the following query:

INSERT INTO category(category_name) VALUES
('Baby'),('Womans Fashion'),('Mens Fashion');

The SQL command above will insert 3 records data into a "category" table.

After that, Insert some data into the "sub_category" table by executing the following query:

INSERT INTO sub_category(subcategory_name,subcategory_category_id) VALUES
('Baby Care','1'),('Baby Stationery','1'),(' Baby & Toddler Toys','1'),
('Clothing','2'),('Shoes','2'),('Jewelry','2'),
('Clothing','3'),('Watches','3'),('Contemporary','3');

The SQL command above will insert 9 records data into a "sub_category" table.

 

Step #3. Installing and Configuring Codeigniter

Extract Codeigniter that you have downloaded earlier to the directory: “C:wampwww” if you use WAMPSERVER.

Or to the directory: “C:xampphtdocs” if you use XAMPP.

Then rename the CodeIgniter project to be “select-ajax”.

Consider the following picture for more details:

Project Name

Next, create a folder "assets" in the "select-ajax" folder parallel to the application and system folder.

Like the picture below:

Assets Folder

After that, extract the Bootstrap file that was previously downloaded into the "assets" folder as shown below:

Bootstrap Files

Next, copy the jquery file into the folder "assets/js" as shown below:

Jquery File

If you haven't got jquery, visit the following URL:

https://code.jquery.com/jquery-3.3.1.js

Select all the code (CTRL + A) and copy then paste it in notepad and save it as jquery-3.3.1.js.

 

Codeigniter configuration:

Next, configure the following file:

1.  Autoload.php

Open the autoload.php file in the "application/config" folder and find the following code:

$autoload['libraries'] = array();
$autoload['helper'] = array();

Then set it to be as follows:

$autoload['libraries'] = array('database');
$autoload['helper'] = array('url');

2.  Config.php

Open the config.php file in the "application/config" folder and find the following code:

$config['base_url'] = '';

Then set it to be as follows:

$config['base_url'] = 'http://localhost/select-ajax/';

Note: if your web server uses a port, include also the port you are using.

3.  Database.php

Open the database.php file in the "application/config" folder and find the following code:

$active_group = 'default';
$query_builder = TRUE;

$db['default'] = array(
        'dsn'   => '',
        'hostname' => 'localhost',
        'username' => '',
        'password' => '',
        'database' => '',
        'dbdriver' => 'mysqli',
        'dbprefix' => '',
        'pconnect' => FALSE,
        'db_debug' => (ENVIRONMENT !== 'production'),
        'cache_on' => FALSE,
        'cachedir' => '',
        'char_set' => 'utf8',
        'dbcollat' => 'utf8_general_ci',
        'swap_pre' => '',
        'encrypt' => FALSE,
        'compress' => FALSE,
        'stricton' => FALSE,
        'failover' => array(),
        'save_queries' => TRUE
);

Then set it to be as follows:

$active_group = 'default';
$query_builder = TRUE;

$db['default'] = array(
        'dsn'   => '',
        'hostname' => 'localhost',
        'username' => 'root',
        'password' => '',
        'database' => 'pos_db',
        'dbdriver' => 'mysqli',
        'dbprefix' => '',
        'pconnect' => FALSE,
        'db_debug' => (ENVIRONMENT !== 'production'),
        'cache_on' => FALSE,
        'cachedir' => '',
        'char_set' => 'utf8',
        'dbcollat' => 'utf8_general_ci',
        'swap_pre' => '',
        'encrypt' => FALSE,
        'compress' => FALSE,
        'stricton' => FALSE,
        'failover' => array(),
        'save_queries' => TRUE
);

 

Step #4. Basic Dependent dropdown in Codeigniter and Ajax

In this step, you will learn the basics of select options dependent using Codeigniter and Ajax.

Let’s begin.

#1. Model

Create a model file named "Product_model.php" in the "application/models" folder.

Then type the following code:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Product_model extends CI_Model{
        
        function get_category(){
                $query = $this->db->get('category');
                return $query;  
        }

        function get_sub_category($category_id){
                $query = $this->db->get_where('sub_category', array('subcategory_category_id' => $category_id));
                return $query;
        }
        
}

#2. Controller

Create a controller file named "Product.php" in the "application/controllers" folder.

Kemudian ketikan kode berikut:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Product extends CI_Controller {
        function __construct(){
                parent::__construct();
                $this->load->model('Product_model','product_model');
        }

        function index(){
                $data['category'] = $this->product_model->get_category()->result();
                $this->load->view('product_view', $data);
        }

        function get_sub_category(){
                $category_id = $this->input->post('id',TRUE);
                $data = $this->product_model->get_sub_category($category_id)->result();
                echo json_encode($data);
        }
}

#3. View

Create a view file named "product_view.php" in the "application/views" folder.

Then type the following code:

<!DOCTYPE html>
<html>
<head>
        <title>Dynamic Select Option using Codeigniter and Ajax</title>
        <link href="<?php echo base_url().'assets/css/bootstrap.css'?>" rel="stylesheet" type="text/css">
</head>
<body>
        <div class="container">

          <div class="row justify-content-md-center">
            <div class="col col-lg-6">
                <h3>Product Form:</h3>
                <form>
                                   <div class="form-group">
                                    <label>Category</label>
                                    <select class="form-control" name="category" id="category" required>
                                        <option value="">No Selected</option>
                                        <?php foreach($category as $row):?>
                                        <option value="<?php echo $row->category_id;?>"><?php echo $row->category_name;?></option>
                                        <?php endforeach;?>
                                    </select>
                                  </div>
                                  <div class="form-group">
                                    <label>Sub Category</label>
                                    <select class="form-control" id="sub_category" name="sub_category" required>
                                        <option>No Selected</option>

                                    </select>
                                  </div>
                        </form>
            </div>
          </div>

        </div>
        <script type="text/javascript" src="<?php echo base_url().'assets/js/jquery-3.3.1.js'?>"></script>
        <script type="text/javascript" src="<?php echo base_url().'assets/js/bootstrap.js'?>"></script>
        <script type="text/javascript">
                $(document).ready(function(){

                        $('#category').change(function(){ 
                var id=$(this).val();
                $.ajax({
                    url : "<?php echo site_url('product/get_sub_category');?>",
                    method : "POST",
                    data : {id: id},
                    async : true,
                    dataType : 'json',
                    success: function(data){
                        
                        var html = '';
                        var i;
                        for(i=0; i<data.length; i++){
                            html += '<option value='+data[i].subcategory_id+'>'+data[i].subcategory_name+'</option>';
                        }
                        $('#sub_category').html(html);

                    }
                });
                return false;
            }); 
            
                });
        </script>
</body>
</html>

#4. Testing

To do the test, open your browser and visit the following URL:

http://localhost/select-ajax/index.php/product

Then, it will appear as shown below:

Product Form

Select one option on "Category", then the option will appear from the "Sub Category" that corresponds.

Like the following picture:

Select Option Dependent

In the picture above, I chose the category "Womens Fashion", then the Sub Category will only appear in accordance with the selected category, namely: Clothing, Shoes, and Jewelry.

If you choose a different category, different Sub Category options will also appear.

That is the basic concept of Select Option related in Codeigniter and Ajax.

 

Step #5. Insert with Select Option dependent in Codeigniter and Ajax

In this step, you will learn how to insert data into a database using select options dependent in Codeigniter and AJAX JQuery.

Let’s dive right in.

#1. Controller

Open the "Product.php" controller in the "application/controllers" folder.

Then change it to be like the code below:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Product extends CI_Controller {
        function __construct(){
                parent::__construct();
                $this->load->model('Product_model','product_model');
                $this->load->library('session');
        }

        function index(){
                
        }

        // add new product
        function add_new(){
                $data['category'] = $this->product_model->get_category()->result();
                $this->load->view('add_product_view', $data);
        }

        // get sub category by category_id
        function get_sub_category(){
                $category_id = $this->input->post('id',TRUE);
                $data = $this->product_model->get_sub_category($category_id)->result();
                echo json_encode($data);
        }

        //save product to database
        function save_product(){
                $product_name   = $this->input->post('product_name',TRUE);
                $category_id    = $this->input->post('category',TRUE);
                $subcategory_id = $this->input->post('sub_category',TRUE);
                $product_price  = $this->input->post('product_price',TRUE);
                $this->product_model->save_product($product_name,$category_id,$subcategory_id,$product_price);
                $this->session->set_flashdata('msg','<div class="alert alert-success">Product Saved</div>');
                redirect('product/add_new');
        }
}

#2. Model

Open the "Product_model.php" model in the "application/models" folder.

Then change it to be like the code below:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Product_model extends CI_Model{
        
        function get_category(){
                $query = $this->db->get('category');
                return $query;  
        }

        function get_sub_category($category_id){
                $query = $this->db->get_where('sub_category', array('subcategory_category_id' => $category_id));
                return $query;
        }
        
        function save_product($product_name,$category_id,$subcategory_id,$product_price){
                $data = array(
                        'product_name' => $product_name,
                        'product_price' => $product_price,
                        'product_category_id' => $category_id,
                        'product_subcategory_id' => $subcategory_id 
                );
                $this->db->insert('product',$data);
        }
}

#3. View

Create a new view named "add_product_view.php" in the "application/views" folder.

Then type the following code:

<!DOCTYPE html>
<html>
<head>
        <title>Add New</title>
        <link href="<?php echo base_url().'assets/css/bootstrap.css'?>" rel="stylesheet" type="text/css">
</head>
<body>
        <div class="container">

          <div class="row justify-content-md-center">
            <div class="col col-lg-6">
                <h3>Add New Product:</h3>
                <?php echo $this->session->flashdata('msg');?>
                <form action="<?php echo site_url('product/save_product');?>" method="post">

                        <div class="form-group">
                                    <label>Product Name</label>
                                    <input type="text" class="form-control" name="product_name" placeholder="Product Name" required>
                                </div>

                                <div class="form-group">
                                    <label>Category</label>
                                    <select class="form-control" name="category" id="category" required>
                                        <option value="">No Selected</option>
                                        <?php foreach($category as $row):?>
                                        <option value="<?php echo $row->category_id;?>"><?php echo $row->category_name;?></option>
                                        <?php endforeach;?>
                                    </select>
                                </div>

                                <div class="form-group">
                                    <label>Sub Category</label>
                                    <select class="form-control" id="sub_category" name="sub_category" required>
                                        <option value="">No Selected</option>

                                    </select>
                                </div>

                                <div class="form-group">
                                    <label>Product Price</label>
                                    <input type="number" class="form-control" name="product_price" placeholder="Product Price" required>
                                </div>

                                <button class="btn btn-success" type="submit">Save Product</button>

                        </form>
            </div>
          </div>

        </div>
        <script type="text/javascript" src="<?php echo base_url().'assets/js/jquery-3.3.1.js'?>"></script>
        <script type="text/javascript" src="<?php echo base_url().'assets/js/bootstrap.js'?>"></script>
        <script type="text/javascript">
                $(document).ready(function(){

                        $('#category').change(function(){ 
                var id=$(this).val();
                $.ajax({
                    url : "<?php echo site_url('product/get_sub_category');?>",
                    method : "POST",
                    data : {id: id},
                    async : true,
                    dataType : 'json',
                    success: function(data){
                        
                        var html = '';
                        var i;
                        for(i=0; i<data.length; i++){
                            html += '<option value='+data[i].subcategory_id+'>'+data[i].subcategory_name+'</option>';
                        }
                        $('#sub_category').html(html);

                    }
                });
                return false;
            }); 
            
                });
        </script>
</body>
</html>

#4. Testing

To do the test, open your browser and visit the following URL:

http://localhost/select-ajax/index.php/product/add_new

Then, it will appear as shown below:

Add new Product

Then input product name, category, sub category, and product price.

Then click the "Save Product" button to save the product to the database.

If it is running well, then it will look like the following picture:

Product Saved

 

Step #6. Displays data that has been inserted into datatable

Extract the Datatable file that was previously downloaded into the "assets" folder.

Extract the datatables.css file into the "assets/css" folder and datatables.js into the "assets/js" folder.

Consider the following picture for more details:

Datatable Files

After that, follow the steps below:

#1. Controller

Open the "Product.php" controller in the "application/controllers" folder.

Then change it to be like the code below:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Product extends CI_Controller {
        function __construct(){
                parent::__construct();
                $this->load->model('Product_model','product_model');
                $this->load->library('session');
        }

        function index(){
                $data['products'] = $this->product_model->get_products();
                $this->load->view('product_list_view',$data);
        }

        // add new product
        function add_new(){
                $data['category'] = $this->product_model->get_category()->result();
                $this->load->view('add_product_view', $data);
        }

        // get sub category by category_id
        function get_sub_category(){
                $category_id = $this->input->post('id',TRUE);
                $data = $this->product_model->get_sub_category($category_id)->result();
                echo json_encode($data);
        }

        //save product to database
        function save_product(){
                $product_name   = $this->input->post('product_name',TRUE);
                $category_id    = $this->input->post('category',TRUE);
                $subcategory_id = $this->input->post('sub_category',TRUE);
                $product_price  = $this->input->post('product_price',TRUE);
                $this->product_model->save_product($product_name,$category_id,$subcategory_id,$product_price);
                $this->session->set_flashdata('msg','<div class="alert alert-success">Product Saved</div>');
                redirect('product');
        }
}

#2. Model

Open the "Product_model.php" model in the "application/models" folder.

Then change it to be like the code below:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Product_model extends CI_Model{
        
        function get_category(){
                $query = $this->db->get('category');
                return $query;  
        }

        function get_sub_category($category_id){
                $query = $this->db->get_where('sub_category', array('subcategory_category_id' => $category_id));
                return $query;
        }
        
        function save_product($product_name,$category_id,$subcategory_id,$product_price){
                $data = array(
                        'product_name' => $product_name,
                        'product_price' => $product_price,
                        'product_category_id' => $category_id,
                        'product_subcategory_id' => $subcategory_id 
                );
                $this->db->insert('product',$data);
        }

        function get_products(){
                $this->db->select('product_id,product_name,product_price,category_name,subcategory_name');
                $this->db->from('product');
                $this->db->join('category','product_category_id = category_id','left');
                $this->db->join('sub_category','product_subcategory_id = subcategory_id','left'); 
                $query = $this->db->get();
                return $query;
        }
}

#3. View

Create a new view named "product_list_view.php" in the "application/views" folder.

Then type the following code:

<!DOCTYPE html>
<html>
<head>
        <title>Product List</title>
        <link href="<?php echo base_url().'assets/css/bootstrap.css'?>" rel="stylesheet" type="text/css">
        <link href="<?php echo base_url().'assets/css/datatables.css'?>" rel="stylesheet" type="text/css">
</head>
<body>
        <div class="container">

          <div class="row justify-content-md-center">
            <div class="col col-lg-8">
                <h3>Product List</h3>
                <?php echo $this->session->flashdata('msg');?>
                <a href="<?php echo site_url('product/add_new');?>" class="btn btn-success btn-sm">Add New Product</a><hr/>
                <table class="table table-striped" id="mytable" style="font-size: 14px;">
                        <thead>
                                <tr>
                                        <th>No</th>
                                        <th>Product Name</th>
                                        <th>Category</th>
                                        <th>Sub Category</th>
                                        <th>Price</th>
                                        <th>Action</th>
                                </tr>
                        </thead>
                        <tbody>
                                <?php
                                        $no = 0;
                                        foreach ($products->result() as $row):
                                                $no++;
                                ?>
                                <tr>
                                        <td><?php echo $no;?></td>
                                        <td><?php echo $row->product_name;?></td>
                                        <td><?php echo $row->category_name;?></td>
                                        <td><?php echo $row->subcategory_name;?></td>
                                        <td><?php echo number_format($row->product_price);?></td>
                                        <td>
                                                <a href="" class="btn btn-sm btn-info">Edit</a>
                                                <a href="" class="btn btn-sm btn-danger">Delete</a>
                                        </td>
                                </tr>
                                <?php endforeach;?>
                        </tbody>
                </table>
            </div>
          </div>

        </div>
        <script type="text/javascript" src="<?php echo base_url().'assets/js/jquery-3.3.1.js'?>"></script>
        <script type="text/javascript" src="<?php echo base_url().'assets/js/bootstrap.js'?>"></script>
        <script type="text/javascript" src="<?php echo base_url().'assets/js/datatables.js'?>"></script>
        <script type="text/javascript">
                $(document).ready(function(){
                        $('#mytable').DataTable();
                });
        </script>
</body>
</html>

#4. Testing

To do the test, open your browser and visit the following URL:

http://localhost/select-ajax/index.php/product

Then, it will appear as shown below:

Product List

Click the "Add New Product" button to add a new product.

Add New Product

Input all inputs, then click the "Save Product" button.

If it is running well, it will appear as follows:

Product Saved

 

Step #7. Update with Select Option dependent in Codeigniter and Ajax

At this step, I will share how to update data with select options dependent on Codeigniter and AJAX.

Let’s dive right in.

First, open the view file "product_list_view.php" which is in the "application/views" folder.

Then find the following code:

<a href="" class="btn btn-sm btn-info">Edit</a>

 Then change it to be like the code below:

<a href="<?php echo site_url('product/get_edit/'.$row->product_id);?>" class="btn btn-sm btn-info">Edit</a> 

After that, follow the steps below:

#1. Controller

Open the "Product.php" controller in the "application / controllers" folder.

Then change it to be like this:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Product extends CI_Controller {
        function __construct(){
                parent::__construct();
                $this->load->model('Product_model','product_model');
                $this->load->library('session');
        }

        function index(){
                $data['products'] = $this->product_model->get_products();
                $this->load->view('product_list_view',$data);
        }

        // add new product
        function add_new(){
                $data['category'] = $this->product_model->get_category()->result();
                $this->load->view('add_product_view', $data);
        }

        // get sub category by category_id
        function get_sub_category(){
                $category_id = $this->input->post('id',TRUE);
                $data = $this->product_model->get_sub_category($category_id)->result();
                echo json_encode($data);
        }

        //save product to database
        function save_product(){
                $product_name   = $this->input->post('product_name',TRUE);
                $category_id    = $this->input->post('category',TRUE);
                $subcategory_id = $this->input->post('sub_category',TRUE);
                $product_price  = $this->input->post('product_price',TRUE);
                $this->product_model->save_product($product_name,$category_id,$subcategory_id,$product_price);
                $this->session->set_flashdata('msg','<div class="alert alert-success">Product Saved</div>');
                redirect('product');
        }

        function get_edit(){
                $product_id = $this->uri->segment(3);
                $data['product_id'] = $product_id;
                $data['category'] = $this->product_model->get_category()->result();
                $get_data = $this->product_model->get_product_by_id($product_id);
                if($get_data->num_rows() > 0){
                        $row = $get_data->row_array();
                        $data['sub_category_id'] = $row['product_subcategory_id'];
                }
                $this->load->view('edit_product_view',$data);
        }

        function get_data_edit(){
                $product_id = $this->input->post('product_id',TRUE);
                $data = $this->product_model->get_product_by_id($product_id)->result();
                echo json_encode($data);
        }

        //update product to database
        function update_product(){
                $product_id     = $this->input->post('product_id',TRUE);
                $product_name   = $this->input->post('product_name',TRUE);
                $category_id    = $this->input->post('category',TRUE);
                $subcategory_id = $this->input->post('sub_category',TRUE);
                $product_price  = $this->input->post('product_price',TRUE);
                $this->product_model->update_product($product_id,$product_name,$category_id,$subcategory_id,$product_price);
                $this->session->set_flashdata('msg','<div class="alert alert-success">Product Updated</div>');
                redirect('product');
        }
}

#2. Model

Open the "Product_model.php" model in the "application/models" folder.

Then change it to be like this:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Product_model extends CI_Model{
        
        function get_category(){
                $query = $this->db->get('category');
                return $query;  
        }

        function get_sub_category($category_id){
                $query = $this->db->get_where('sub_category', array('subcategory_category_id' => $category_id));
                return $query;
        }
        
        function save_product($product_name,$category_id,$subcategory_id,$product_price){
                $data = array(
                        'product_name' => $product_name,
                        'product_price' => $product_price,
                        'product_category_id' => $category_id,
                        'product_subcategory_id' => $subcategory_id 
                );
                $this->db->insert('product',$data);
        }

        function get_products(){
                $this->db->select('product_id,product_name,product_price,category_name,subcategory_name');
                $this->db->from('product');
                $this->db->join('category','product_category_id = category_id','left');
                $this->db->join('sub_category','product_subcategory_id = subcategory_id','left'); 
                $query = $this->db->get();
                return $query;
        }

        function get_product_by_id($product_id){
                $query = $this->db->get_where('product', array('product_id' =>  $product_id));
                return $query;
        }

        function update_product($product_id,$product_name,$category_id,$subcategory_id,$product_price){
                $this->db->set('product_name', $product_name);
                $this->db->set('product_price', $product_price);
                $this->db->set('product_category_id', $category_id);
                $this->db->set('product_subcategory_id', $subcategory_id);
                $this->db->where('product_id', $product_id);
                $this->db->update('product');
        }

        
}

#3. View

Create a new view with the name "edit_product_view.php" in the "application/views" folder.

Then type the following code:

<!DOCTYPE html>
<html>
<head>
        <title>Edit Product</title>
        <link href="<?php echo base_url().'assets/css/bootstrap.css'?>" rel="stylesheet" type="text/css">
</head>
<body>
        <div class="container">

          <div class="row justify-content-md-center">
            <div class="col col-lg-6">
                <h3>Edit Product:</h3>
                
                <form action="<?php echo site_url('product/update_product');?>" method="post">

                        <div class="form-group">
                                    <label>Product Name</label>
                                    <input type="text" class="form-control" name="product_name" placeholder="Product Name" required>
                                </div>

                                <div class="form-group">
                                    <label>Category</label>
                                    <select class="form-control category" name="category" required>
                                        <option value="">No Selected</option>
                                        <?php foreach($category as $row):?>
                                        <option value="<?php echo $row->category_id;?>"><?php echo $row->category_name;?></option>
                                        <?php endforeach;?>
                                    </select>
                                </div>

                                <div class="form-group">
                                    <label>Sub Category</label>
                                    <select class="form-control sub_category" name="sub_category" required>
                                        <option value="">No Selected</option>

                                    </select>
                                </div>

                                <div class="form-group">
                                    <label>Product Price</label>
                                    <input type="number" class="form-control" name="product_price" placeholder="Product Price" required>
                                </div>

                                <input type="hidden" name="product_id" value="<?php echo $product_id?>" required>
                                <button class="btn btn-success" type="submit">Update Product</button>

                        </form>
            </div>
          </div>

        </div>
        <script type="text/javascript" src="<?php echo base_url().'assets/js/jquery-3.3.1.js'?>"></script>
        <script type="text/javascript" src="<?php echo base_url().'assets/js/bootstrap.js'?>"></script>
        <script type="text/javascript">
                $(document).ready(function(){
                        //call function get data edit
                        get_data_edit();

                        $('.category').change(function(){ 
                var id=$(this).val();
                var subcategory_id = "<?php echo $sub_category_id;?>";
                $.ajax({
                    url : "<?php echo site_url('product/get_sub_category');?>",
                    method : "POST",
                    data : {id: id},
                    async : true,
                    dataType : 'json',
                    success: function(data){

                        $('select[name="sub_category"]').empty();

                        $.each(data, function(key, value) {
                            if(subcategory_id==value.subcategory_id){
                                $('select[name="sub_category"]').append('<option value="'+ value.subcategory_id +'" selected>'+ value.subcategory_name +'</option>').trigger('change');
                            }else{
                                $('select[name="sub_category"]').append('<option value="'+ value.subcategory_id +'">'+ value.subcategory_name +'</option>');
                            }
                        });

                    }
                });
                return false;
            }); 

                        //load data for edit
            function get_data_edit(){
                var product_id = $('[name="product_id"]').val();
                $.ajax({
                        url : "<?php echo site_url('product/get_data_edit');?>",
                    method : "POST",
                    data :{product_id :product_id},
                    async : true,
                    dataType : 'json',
                    success : function(data){
                        $.each(data, function(i, item){
                            $('[name="product_name"]').val(data[i].product_name);
                            $('[name="category"]').val(data[i].product_category_id).trigger('change');
                            $('[name="sub_category"]').val(data[i].product_subcategory_id).trigger('change');
                            $('[name="product_price"]').val(data[i].product_price);
                        });
                    }

                });
            }
            
                });
        </script>
</body>
</html>

#4. Testing

To do the test, open your browser and visit the following URL:

http://localhost/select-ajax/index.php/product

Then, it will appear as shown below:

Product List Edit

Then click the “edit” button, then the edit form will appear as shown below:

Edit Form

Edit the data you want to edit, then click the "Update Product" button.

If it is running well, it will look like the following picture:

Product Updated

 

Step #8. Delete data to the database

At this step, I will share how to delete data to the database.

Let’s begin.

First of all, open the view file "product_list_view.php" in the "application/views" folder.

Then find the following code:

<a href="" class="btn btn-sm btn-danger">Delete</a>

Then change it to be like the following code:

<a href="<?php echo site_url('product/delete/'.$row->product_id);?>" class="btn btn-sm btn-danger">Delete</a> 

After that, follow the steps below:

#1. Controller

Open the "Product.php" controller in the "application/controllers" folder.

Then add the delete function below:

function delete(){
        $product_id = $this->uri->segment(3);
        $this->product_model->delete_product($product_id);
        $this->session->set_flashdata('msg','<div class="alert alert-success">Product Deleted</div>');
        redirect('product');
}

#2. Model

Open the "Product_model.php" model in the "application/models" folder.

Then add the "delete_product" function below:

function delete_product($product_id){
        $this->db->delete('product', array('product_id' => $product_id));
}

#3. Testing

To do the test, open your browser and visit the following URL:

http://localhost/select-ajax/index.php/product

Then click one of the "Delete" buttons to delete the data.

If it is running well, it will look like the following picture:

Product Deleted

Conclusion:

This tutorial is about how to create select options dependent using Codeigniter and AJAX.

Starting from preparation, database creation and tables, Codeigniter installation, Codeigniter configuration, up to CRUD (Create Read Update Delete) with select dependent options using CodeIgniter and Ajax.

So what are you waiting for, Let’s Coding.!

Download Source Code

Comments (7)

Maroof Khan, 04 April 2019 18:11 -

Great job keep it up MFikri

M Fikri, 06 April 2019 07:46 -

Thank You.

Alessandro, 29 September 2020 00:04 -

Same thing for CodeIgniter 4 please.

NYoman Gunartha, 07 January 2021 09:40 -

thank you for sharing, good job..

Ajesh, 08 May 2021 14:50 -

I have gone through many tutorials before. I haven't found anything near to this both in quality and simplicity. Thanks a ton, mfikri!

archana, 07 July 2021 12:59 -

thank u for this coding.. it very useful for me

Fitriansyah Ahmad, 14 June 2022 06:08 -

Thanks, you're excelent

Leave a Comment