Codeigniter 4 Dynamic Dependent Dropdown with Ajax Tutorial

In this tutorial, we will learn how to create a dynamic dependent dropdown in Codeigniter 4 using Ajax. We will use jQuery and Ajax to fetch data from the database and display it in the dropdown list.

We will create a simple Codeigniter 4 application with a dynamic dependent dropdown list. We will use jQuery and Ajax to fetch data from the database and display it in the dropdown list.

We will create two tables in the database. The first table will contain the list of countries and the second table will contain the list of states for each country. We will use the jQuery and Ajax to fetch the data from the database and display it in the dropdown list.

We will create a simple form with two dropdown lists. The first dropdown list will contain the list of countries and the second dropdown list will contain the list of states for the selected country.

We will use the jQuery and Ajax to fetch the data from the database and display it in the dropdown list. We will also use the Codeigniter 4 form validation library to validate the form data.

So, let’s get started with the tutorial.

Step 1: Create the Database Tables

First, we will create two tables in the database. The first table will contain the list of countries and the second table will contain the list of states for each country.

We will use the following SQL query to create the countries table.

CREATE TABLE `countries` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

We will use the following SQL query to create the states table.

CREATE TABLE `states` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`country_id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
KEY `country_id` (`country_id`),
CONSTRAINT `states_ibfk_1` FOREIGN KEY (`country_id`) REFERENCES `countries` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Step 2: Create the Models

Next, we will create two models for the countries and states tables. We will use the Codeigniter 4 Model class to create the models.

We will create a Country model for the countries table.

request->getPost(‘country_id’);
$states = State::where(‘country_id’, $country_id)->findAll();
return $this->response->setJSON($states);
}
}

Step 4: Create the View

Next, we will create a view for the dynamic dependent dropdown. We will use the Codeigniter 4 View class to create the view.

We will create a home.php view file for the dynamic dependent dropdown.



Codeigniter 4 Dynamic Dependent Dropdown with Ajax Tutorial


Codeigniter 4 Dynamic Dependent Dropdown with Ajax Tutorial




Step 5: Run the Application

Now, we can run the application and test the dynamic dependent dropdown.

Open the browser and access the application using the following URL.

http://localhost/codeigniter4/public/home

You should see the following output.

Codeigniter 4 Dynamic Dependent Dropdown with Ajax Tutorial

Select Country
Select State

Now, select a country from the dropdown list. You should see the list of states for the selected country in the second dropdown list.

That’s it. You have successfully created a dynamic dependent dropdown in Codeigniter 4 using Ajax.
[ad_1]

To dynamic auto-populate or get a dependent dropdown in Codeigniter 4 with jquery ajax; In this tutorial guide, you will learn how to make a dynamic dependent dropdown to get dynamically or auto-populate second dropdown list to be populated dynamically or automatically based on the selected option from the first dropdown list in Codeigniter 4 with jQuery Ajax and bootstrap.

Dynamic Dependent Dropdown using Ajax in Codeigniter 4

Let’s follow the following steps to create a dynamic dependent dropdown and dynamically populate a second dropdownlist from a first dropDown list using jquery ajax in codeigniter 4 projects:

  • Step 1: Download Codeigniter Project
  • Step 2: Basic Configurations
  • Step 3: Create Database With Table
  • Step 4: Setup Database Credentials
  • Step 5: Create Model File
  • Step 6: Create Controller
  • Step 7: Create Views
  • Step 8: Test App On Browser

Step 1: Download Codeigniter Project

In this step, you will download the latest version of Codeigniter 4, Go to this link https://codeigniter.com/download Download Codeigniter 4 fresh new setup and unzip the setup in your local system xampp/htdocs/ . And change the download folder name “demo”

Step 2: Basic Configurations

Next, you will set some basic configuration on the app/config/app.php file, so let’s go to application/config/config.php and open this file on text editor.

Set Base URL like this

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

Step 3: Create Database With Table

In this step, you need to create a database name demo, so let’s open your PHPMyAdmin and create the database with the name demo. After successfully create a database, you can use the below SQL query for creating a table in your database.

CREATE TABLE `city` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `cityname` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `department` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `depart_name` varchar(80) NOT NULL,
  `city` int(3) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE `user_depart` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `username` varchar(80) NOT NULL,
  `name` varchar(80) NOT NULL,
  `email` varchar(80) NOT NULL,
  `department` int(3) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Step 4: Setup Database Credentials

In this step, you need to connect our project to the database. you need to go app/Config/Database.php and open database.php file in text editor. After opening the file in a text editor, you need to set up database credentials in this file like below.

	public $default = [
		'DSN'      => '',
		'hostname' => 'localhost',
		'username' => 'root',
		'password' => '',
		'database' => 'demo',
		'DBDriver' => 'MySQLi',
		'DBPrefix' => '',
		'pConnect' => false,
		'DBDebug'  => (ENVIRONMENT !== 'production'),
		'cacheOn'  => false,
		'cacheDir' => '',
		'charset'  => 'utf8',
		'DBCollat' => 'utf8_general_ci',
		'swapPre'  => '',
		'encrypt'  => false,
		'compress' => false,
		'strictOn' => false,
		'failover' => [],
		'port'     => 3306,
	];

Step 5: Create Model File

In this step, visit app/Models/ and create here one model named Main_model.php. Then add the following code into your Main_model.php file:

<?php

namespace App\Models;

use CodeIgniter\Model;

class Main_model extends Model {

    
    public function __construct() {
        parent::__construct();
        //$this->load->database();
        $db = \Config\Database::connect();
    }

    public function getCity() {

       $query = $this->db->query('select * from city');
       return $query->getResult();
    }

    public function getCityDepartment($postData) {
      $sql = 'select * from department where city ='.$postData['city'] ;
      $query =  $this->db->query($sql);
      
      return $query->getResult();
    }    

    public function getDepartmentUsers($postData) {
      $sql = 'select * from user_depart where department ='.$postData['department'] ;
      $query =  $this->db->query($sql);
      
      return $query->getResult();
    }


}

Step 6: Create Controller

In this step, Visit app/Controllers and create a controller name Dropdown.php. In this controller, you need to add the following methods into it:

<?php

namespace App\Controllers;

use CodeIgniter\Controller;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use App\Models\Main_model;

class Dropdown extends Controller {


    public function index() {
        
        helper(['form', 'url']);
        $this->Main_model = new Main_model();
        $data['cities'] = $this->Main_model->getCity();
        return view('dropdown-view', $data);
    }

    public function getCityDepartment() {

        $this->Main_model = new Main_model();

        $postData = array(
            'city' => $this->request->getPost('city'),
        );

        $data = $this->Main_model->getCityDepartment($postData);

        echo json_encode($data);
    }    

    public function getDepartmentUsers() {

        $this->Main_model = new Main_model();

        $postData = array(
            'department' => $this->request->getPost('department'),
        );

        $data = $this->Main_model->getDepartmentUsers($postData);

        echo json_encode($data);
    }


}

Step 7: Create Views

In this step, you need to create one view files name dropdown-view.php and update the following 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 Ajax Dependent Dropdown List - Tutsmake.COM</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 Dynamic Dependent Dropdown with Ajax - Tutsmake.COM</h2>
</div>
<div class="card-body">
<form>
<div class="form-group">
<label for="country">City</label>
<select class="form-control" id="sel_city">
<option value="">Select City</option>
<?php foreach($cities as $city){?>
<option value="<?php echo $city->id;?>"><?php echo $city->cityname;?></option>"
<?php }?>
</select>
</div>
<div class="form-group">
<label for="state">Departments</label>
<select class="form-control" id="sel_depart">
</select>
</div>                        
<div class="form-group">
<label for="city">Users</label>
<select class="form-control" id="sel_user">
</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
$('#sel_city').change(function(){
var city = $(this).val();
// AJAX request
$.ajax({
url:'<?=base_url()?>index.php/User/getCityDepartment',
method: 'post',
data: {city: city},
dataType: 'json',
success: function(response){
// Remove options 
$('#sel_user').find('option').not(':first').remove();
$('#sel_depart').find('option').not(':first').remove();
// Add options
$.each(response,function(index,data){
$('#sel_depart').append('<option value="'+data['id']+'">'+data['depart_name']+'</option>');
});
}
});
});
// Department change
$('#sel_depart').change(function(){
var department = $(this).val();
// AJAX request
$.ajax({
url:'<?=base_url()?>index.php/User/getDepartmentUsers',
method: 'post',
data: {department: department},
dataType: 'json',
success: function(response){
// Remove options
$('#sel_user').find('option').not(':first').remove();
// Add options
$.each(response,function(index,data){
$('#sel_user').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 Codeigniter 4 ajax dynamic dropdown example. In this tutorial you have successfully created Dynamic dependent dropdown in Codeigniter 4 with Ajax.

Recommended Codeigniter Posts

If you have any questions or thoughts to share, use the comment form below to reach us.

[ad_2]

Jaspreet Singh Ghuman

Jaspreet Singh Ghuman

Jassweb.com/

Passionate Professional Blogger, Freelancer, WordPress Enthusiast, Digital Marketer, Web Developer, Server Operator, Networking Expert. Empowering online presence with diverse skills.

jassweb logo

Jassweb always keeps its services up-to-date with the latest trends in the market, providing its customers all over the world with high-end and easily extensible internet, intranet, and extranet products.

GSTIN is 03EGRPS4248R1ZD.

Contact
Jassweb, Rai Chak, Punjab, India. 143518
Item added to cart.
0 items - 0.00