Country State City Dependent Dropdown in Codeigniter 4

Codeigniter 4 Country State City Dropdown Using Ajax Example - Lara  Tutorials

Country state and city dynamic dependent dropdown in PHP Codeigniter 4 with Ajax; In this example, you will learn how to implement dynamic dependent country state city dropdown in Codeigniter 4 with Ajax and bootstrap 4.

Dynamic dependent dropdown making in Codeigniter 4 app is very easy using ajax; In this tutorial, with help of Ajax, jQuery, Bootstrap, and MySQL database will create Country State City Dependent dropdown in PHP Codeigniter 4 app.

Codeigniter 4 Country State City Dropdown Using Ajax Example

  • Download Codeigniter Latest
  • Basic Configurations
  • Create Database With Table
  • Setup Database Credentials
  • Create Model File
  • Create Controller
  • Create Views
  • 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 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);

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\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

In this step, Visit app/Controllers and create a controller name DropdownAjaxController.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 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

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 Dependent Country State City Dropdown using Ajax - 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 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

Country state and city dynamic dependent dropdown in Codeigniter 4 with Ajax; In this example, you will learn how to implement dynamic dependent country state city dropdown in Codeigniter 4 with Ajax and bootstrap 4.

Leave a Reply

Your email address will not be published.