Codeigniter 4 Country State City Dropdown Using Ajax Example

20-Apr-2022

.

Admin

Codeigniter 4 Country State City Dropdown Using Ajax Example

Hi Dev,

In this example, I will show you country state city dropdown using ajax in codeigniter 4. This tutorial will give you simple example of country state city dependent dropdown using ajax in codeigniter 4. I would like to share with you country state city dropdown using ajax in php. I explained simply about country state city dropdown using jquery ajax in php.

This article will give you simple example of I would like to share with you country state city dropdown using ajax in php. I explained simply about country state city dropdown using jquery ajax in php.

This tutorial will manual you little by little on a way to integrate country state city dropdown using ajax in codeigniter 4.

So let's start to the example.

Step 1: Install Codeigniter 4


This is optional; however, if you have not created the codeigniter app, then you may go ahead and execute the below command:

composer create-project codeigniter4/appstarter ci-news

After Download successfully, extract clean new Codeigniter 4 application.

Step 2 : Basic Configurations

So, we will now set basic configuration on the app/config/app.php file, so let’s implement to application/config/config.php and open this file on text editor.

app/config/app.php

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

To

public $baseURL = 'http://localhost/example/';

Step 3 : Database Configurations

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 : Database Configurations

application/config/database.php

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

in this step we will create a model file MainModel.php and then following below code.

<?php

namespace App\Controllers;

use CodeIgniter\Controller;

use CodeIgniter\HTTP\RequestInterface;

use CodeIgniter\HTTP\ResponseInterface;

use App\Models\MainModel;

class DropdownAjaxController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index() {

helper(['form', 'url']);

$this->MainModel = new MainModel();

$data['countries'] = $this->MainModel->getCountries();

return view('dropdown-list', $data);

}

/**

* Write code on Method

*

* @return response()

*/

public function getStates() {

$this->MainModel = new MainModel();

$postData = array(

'country_id' => $this->request->getPost('country_id'),

);

$data = $this->MainModel->getStates($postData);

echo json_encode($data);

}

/**

* Write code on Method

*

* @return response()

*/

public function getCities() {

$this->MainModel = new MainModel();

$postData = array(

'state_id' => $this->request->getPost('state_id'),

);

$data = $this->MainModel->getCities($postData);

echo json_encode($data);

}

}

Step 6 : Set Up Controller

Further, you need to generate a new controller that manages the online stripe transaction, hence create a DropdownAjaxController file and append the example code in..

app/Controllers/DropdownAjaxController.php

<?php

namespace App\Controllers;

use CodeIgniter\Controller;

use CodeIgniter\HTTP\RequestInterface;

use CodeIgniter\HTTP\ResponseInterface;

use App\Models\MainModel;

class DropdownAjaxController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index() {

helper(['form', 'url']);

$this->MainModel = new MainModel();

$data['countries'] = $this->MainModel->getCountries();

return view('dropdown-view', $data);

}

/**

* Write code on Method

*

* @return response()

*/

public function getStates() {

$this->MainModel = new MainModel();

$postData = array(

'country_id' => $this->request->getPost('country_id'),

);

$data = $this->MainModel->getStates($postData);

echo json_encode($data);

}

/**

* Write code on Method

*

* @return response()

*/

public function getCities() {

$this->MainModel = new MainModel();

$postData = array(

'state_id' => $this->request->getPost('state_id'),

);

$data = $this->MainModel->getCities($postData);

echo json_encode($data);

}

}

Step 7 : Set Up View

Head over to application/views/ folder, create a new dropdown-view.php file. Likewise, open and add the suggested code example in application/views/dropdown-view.php file:

application/views/dropdown-view.php

<!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 - Nicesnippets.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 - Nicesnippets.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({

url:'<?=base_url()?>/DropdownAjaxController/getStates',

method: 'post',

data: {country_id: country_id},

dataType: 'json',

success: function(response){

$('#state_id').find('option').not(':first').remove();

$('#city_id').find('option').not(':first').remove();

$.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({

url:'<?=base_url()?>/DropdownAjaxController/getCities',

method: 'post',

data: {state_id: state_id},

dataType: 'json',

success: function(response){

$('#city_id').find('option').not(':first').remove();

$.each(response,function(index,data){

$('#city_id').append('<option value="'+data['id']+'">'+data['name']+'</option>');

});

}

});

});

});

</script>

</body>

</html>

Step 8 : Run Codeigniter App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Codeigniter app:

php spark serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8080/

I hope it can help you...

#Codeigniter 4