Country State City Dependent Dropdown using Ajax in Codeigniter

Country State City Dependent Dropdown using Ajax in Codeigniter step by step process:

Step 1: Set Up CodeIgniter 4

Begin by downloading CodeIgniter 4 from the official site: https://codeigniter.com/user_guide/installation/index.html. Extract the ZIP file into the xampp/htdocs directory.

Update the .env file to configure your database connection as follows:

database.default.hostname = localhost
database.default.database = your_database_name
database.default.username = your_username
database.default.password = your_password
database.default.DBDriver = MySQLi

Step 2: Create Tables for Country, State, and City

Execute the SQL queries below to establish the countries, states, and cities tables:

CREATE TABLE countries (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL
);

CREATE TABLE states (
id INT AUTO_INCREMENT PRIMARY KEY,
country_id INT NOT NULL,
name VARCHAR(100) NOT NULL,
FOREIGN KEY (country_id) REFERENCES countries(id)
);

CREATE TABLE cities (
id INT AUTO_INCREMENT PRIMARY KEY,
state_id INT NOT NULL,
name VARCHAR(100) NOT NULL,
FOREIGN KEY (state_id) REFERENCES states(id)
);

Use these insert statements to populate the tables with initial data:

INSERT INTO countries (name) VALUES ('USA'), ('Canada'), ('India');

INSERT INTO states (country_id, name) VALUES
(1, 'California'), (1, 'Texas'), (1, 'New York'),
(2, 'Ontario'), (2, 'Quebec'), (2, 'British Columbia'),
(3, 'Maharashtra'), (3, 'Gujarat'), (3, 'Rajasthan');

INSERT INTO cities (state_id, name) VALUES
(1, 'Los Angeles'), (1, 'San Francisco'), (1, 'San Diego'),
(2, 'Houston'), (2, 'Dallas'), (2, 'Austin'),
(3, 'New York City'), (3, 'Buffalo'), (3, 'Rochester'),
(4, 'Toronto'), (4, 'Ottawa'), (4, 'Mississauga'),
(5, 'Montreal'), (5, 'Quebec City'), (5, 'Laval'),
(6, 'Vancouver'), (6, 'Victoria'), (6, 'Surrey'),
(7, 'Mumbai'), (7, 'Pune'), (7, 'Nagpur'),
(8, 'Ahmedabad'), (8, 'Surat'), (8, 'Vadodara'),
(9, 'Jaipur'), (9, 'Udaipur'), (9, 'Jodhpur');

Step 3: Develop the Models

In the app/Models directory, create the model files for country, state, and city:

CountryModel.php

<?php

namespace App\Models;

use CodeIgniter\Model;

class CountryModel extends Model
{
protected $table = 'countries';
protected $primaryKey = 'id';
protected $allowedFields = ['name'];
}

StateModel.php

<?php

namespace App\Models;

use CodeIgniter\Model;

class StateModel extends Model
{
protected $table = 'states';
protected $primaryKey = 'id';
protected $allowedFields = ['country_id', 'name'];
}

CityModel.php

<?php

namespace App\Models;

use CodeIgniter\Model;

class CityModel extends Model
{
protected $table = 'cities';
protected $primaryKey = 'id';
protected $allowedFields = ['state_id', 'name'];
}

Step 4: Create the Controller

Create a file named LocationController.php in the app/Controllers directory to manage the business logic:

<?php

namespace App\Controllers;

use App\Models\CountryModel;
use App\Models\StateModel;
use App\Models\CityModel;
use CodeIgniter\Controller;

class LocationController extends Controller
{
public function index()
{
$countryModel = new CountryModel();
$data['countries'] = $countryModel->findAll();
return view('location_view', $data);
}

public function fetchStates()
{
$stateModel = new StateModel();
$countryId = $this->request->getPost('country_id');
$states = $stateModel->where('country_id', $countryId)->findAll();
echo json_encode($states);
}

public function fetchCities()
{
$cityModel = new CityModel();
$stateId = $this->request->getPost('state_id');
$cities = $cityModel->where('state_id', $stateId)->findAll();
echo json_encode($cities);
}
}

Step 5: Build the View

In the app/Views directory, create a file named location_view.php to display the dependent dropdowns:

<!DOCTYPE html>
<html>
<head>
<title>Dynamic Dependent Dropdown in CodeIgniter 4 - itcodstuff.com</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>Dynamic Dependent Dropdown in CodeIgniter 4 - itcodstuff.com</h1>
<form>
<label for="country">Country:</label>
<select id="country" name="country">
<option value="">Select Country</option>
<?php foreach ($countries as $country): ?>
<option value="<?= $country['id']; ?>"><?= $country['name']; ?></option>
<?php endforeach; ?>
</select>

<label for="state">State:</label>
<select id="state" name="state">
<option value="">Select State</option>
</select>

<label for="city">City:</label>
<select id="city" name="city">
<option value="">Select City</option>
</select>
</form>

</body>
</html>

Step 6: Implement Ajax in the View

Add Ajax code to dynamically load states and cities based on the selected country and state:

<script>
$(document).ready(function() {
$('#country').change(function() {
var countryId = $(this).val();
if (countryId != '') {
$.ajax({
url: "<?= site_url('locationcontroller/fetchstates'); ?>",
method: "POST",
data: {country_id: countryId},
dataType: "json",
success: function(data) {
$('#state').html('<option value="">Select State</option>');
$.each(data, function(key, value) {
$('#state').append('<option value="'+ value.id +'">'+ value.name +'</option>');
});
$('#city').html('<option value="">Select City</option>');
}
});
} else {
$('#state').html('<option value="">Select State</option>');
$('#city').html('<option value="">Select City</option>');
}
});

$('#state').change(function() {
var stateId = $(this).val();
if (stateId != '') {
$.ajax({
url: "<?= site_url('locationcontroller/fetchcities'); ?>",
method: "POST",
data: {state_id: stateId},
dataType: "json",
success: function(data) {
$('#city').html('<option value="">Select City</option>');
$.each(data, function(key, value) {
$('#city').append('<option value="'+ value.id +'">'+ value.name +'</option>');
});
}
});
} else {
$('#city').html('<option value="">Select City</option>');
}
});
});
</script>

Step 7: Set Up Routes

Update the app/Config/Routes.php file to include the necessary routes:

$routes->get('/', 'LocationController::index');
$routes->post('locationcontroller/fetchstates', 'LocationController::fetchStates');
$routes->post('locationcontroller/fetchcities', 'LocationController::fetchCities');

Step 8: Test the Application

Navigate to http://localhost/your_project_name/public/ in your browser to test the functionality of your application.