Codeigniter 4 Country State City Dropdown Using Ajax Example

Country state city dropdown using ajax in codeigniter; In this tutorial, i will show you how to implement dynamic dependent dropdown in PHP Codeigniter 4 using Ajax with jQuery, Mysql and Bootstrap 4 library.

For build dynamic country state city dependent dropdown in codeigniter 4 app, you have to use Ajax jQuery with Codeigniter 4 framework. So in this example, you have make dynamic ountry state city dependent dropdown in Codeigniter 4 using Ajax jQuery. Here you can find step by step guide for build how to create dynamic dependent ountry state city dependent dropdown in PHP Codeigniter 4 using Ajax with jQuery, Mysql and Bootstrap 4 library.

Country state city dropdown in codeigniter 4 using jQuery ajax; In this example tutorial i will guide you step by step on how to implement dependent dropdown using jQuery and ajax in PHP Codeigniter 4 app with populate dynamic data.

For this country state city dependent dropdown in PHP codeigniter 4 using jQuery ajax; In this example, the dependent country state city dependent dropdown will make. In that the first dependent dropdown would be country . When the visitor selects the country, Then the list of states will be populated in the next dropdown. And when the states will select the states from dropdown. Then the list of cities will be populated in the next dropdown .

Country State City Dropdown using Ajax in Codeigniter 4

  • Install Codeigniter 4 Application
  • Basic App Configurations
  • Create Database and Table
  • Setup Database Credentials
  • Create Controller
  • Create Views
  • Setup Routes
  • Start Development server

Step 1 – Install Codeigniter 4 Application

First of all, you need to ownload the latest version of Codeigniter 4. So, visit this link https://codeigniter.com/download Download Codeigniter 4 app and unzip the setup in your local system xampp/htdocs/ .

Note that, please change the download folder name “demo”.

Step 2 – Basic App Configurations

Now, you need to 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 and Table

Create a database and country, state and city table by executing the following SQL query. And as well as, insert data into these tables:

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

To connect your codeigniter 4 app to the database. So, visit app/Config/ directory and open Database.php. Then add the databasae details like below into database.php file:

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

Step 5 – Create Model and Controller

Create CountryStateCity.php file. So, visit app/Modelsdirectory and create CountryStateCity.php.Then add the following code into it:

<?php
 
namespace App\Models;
 
use CodeIgniter\Model;
 
class CountryStateCity extends Model {
 
     
    public function __construct() {
        parent::__construct();
        //$this->load->database();
        $db = \Config\Database::connect();
    }
 
    public function getCountries() {
 
       $query = $this->db->query('select * from countries');
       return $query->getResult();
    }
 
    public function getStates($postData) {
      $sql = 'select * from states where country_id ='.$postData['country_id'] ;
      $query =  $this->db->query($sql);
       
      return $query->getResult();
    }

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

 
 
}

Create CountryStateCityController.php file. So, visit app/Controllers directory and create CountryStateCityController.php.Then add the following code into it:

<?php
 
namespace App\Controllers;
 
use CodeIgniter\Controller;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use App\Models\CountryStateCity;
 
class CountryStateCityController extends Controller {
 
 
    public function index() {
         
        helper(['form', 'url']);
        $this->CountryStateCity = new CountryStateCity();
        $data['countries'] = $this->CountryStateCity->getCountries();
        return view('dropdown-list', $data);
    }

    public function getStates() {
 
        $this->CountryStateCity = new CountryStateCity();
 
        $postData = array(
            'country_id' => $this->request->getPost('country_id'),
        );
 
        $data = $this->CountryStateCity->getStates($postData);
 
        echo json_encode($data);
    }
 
    public function getCities() {
 
        $this->CountryStateCity = new CountryStateCity();
 
        $postData = array(
            'state_id' => $this->request->getPost('state_id'),
        );
 
        $data = $this->CountryStateCity->getCities($postData);
 
        echo json_encode($data);
    }    
 
 
 
}

The methods built into the CountryStateCity controller have the following functions:

  • The index() function renders the country state and city into the view.
  • The getStates() method will fetch data from states table using country id.
  • The getCities() method will fetch data from cities table using state id.

Step 6 – Create Views

Create dropdown-list.php view file, so visit application/views/ directory and create dropdown-list.php file. Then add the following HTML into dropdown-list.php 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 - Laratutorials.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 - Laratutorials.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()?>/CountryStateCityController/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()?>/CountryStateCityController/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 7 – Setup Routes

To define a route, So, visit app/Config/ directory and open Routes.php file. Then add the following routes into it:

$routes->setDefaultController('CountryStateCityController');
$routes->get('/', 'CountryStateCityController::index');

Step 8 – Start Development server

Execute the following command into command prompt or terminal to start the codeigniter 4 application:

php spark serve

Then visit your web browser and hit the following url on it:

http://localhost/demo/

OR

http://localhost:8080/

Conclusion

CodeIgniter 4 dynamic dependent dropdown tutorial. In this example,you have learned how to implement dependent dropdown using jQuery and ajax in PHP Codeigniter 4 app with populate dynamic data.

Recommended CodeIgniter 4 Tutorial

  1. Codeigniter 4 Ajax Form Submit Validation Example
  2. Codeigniter 4 File Upload Validation Example
  3. Codeigniter 4 Image Upload Preview Using jQuery Example
  4. Codeigniter 4 Ajax Image Upload Preview Example
  5. How to Upload Multiple Images in Codeigniter 4
  6. Codeigniter 4 Multiple Image Upload with Preview
  7. Codeigniter 4 Pagination Example; Create Pagination in Codeigniter
  8. Codeigniter 4 CRUD with Datatables Example
  9. CodeIgniter 4 Server Side DataTable Example
  10. Create Rest Api In Codeigniter 4 App
  11. Codeigniter 4 Image Crop and Save using Croppie Example
  12. Codeigniter 4 Dependent Dropdown using jQuery Ajax Example

Be First to Comment

Leave a Reply

Your email address will not be published.