0% found this document useful (0 votes)
285 views8 pages

Country-State-City Example - Cascading JQuery AJAX Dependent Dropdown in PHP - Phppot

Uploaded by

Asma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
285 views8 pages

Country-State-City Example - Cascading JQuery AJAX Dependent Dropdown in PHP - Phppot

Uploaded by

Asma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

04/01/2021 Country-State-City Example: Cascading jQuery AJAX Dependent Dropdown in PHP - Phppot

helping build websites Shop Services Testimonials Blog About Con

eCommerce Country-State-City Example: Cascading jQuery Hi, I’m Vincy. I help build websites
Components AJAX Dependent Dropdown in PHP and I’m available for freelance work.
Files Last modified on November 13th, 2019.
[email protected]
UI
Are you searching for creating a dependent country-state-city dropdown in your
Performance application? I will give you a free download for an AJAX-based dependent Contact Form - Iris
Framework dropdown code. It loads data from the database depends on the selected parent
entity.
PHP

Learn PHP When dropdown options depend on another input, we can say it as a
PHP Introduction dependent dropdown. Instead of user selection, some dropdowns depend on
PHP Basics location, timezone and more. If you want to know how to find users’ locations,
Contact Form then the linked article will help you with an example.
Comments System
Types, Variables &
Operators
PHP Strings
PHP Arrays
PHP Functions
PHP OOPS
“She is cooperative and able to quickly
PHP Forms
understand our needs behind different
Advanced features. We kept the estimated budget a
PHP AJAX within the assumed timeline. ...” read mo
Country-State-City
Example: Cascading Marcin Bialy, Grandmetric, Poland
jQuery AJAX
Dependent Dropdown
in PHP
Load Dependent
Dropdown on Multi-
Select using PHP and
jQuery
AJAX Based Login
Registration System
with jQuery Lightbox
Create AJAX-Based
PHP Event
Management System
with Bootstrap
How to Create
Facebook Like Infinite
Scroll Pagination using view demo
PHP and jQuery
Facebook Like Header
Notification in PHP
In a web application, it may have many requirements around the dropdown
Sorting MySQL Row
Order using jQuery feature. For example, it requires to display cascading dropdowns with group
AJAX Pagination with options. In some applications, it needs dependent dropdowns with multi-select.
PHP
Change Order of There are solutions available on the web to sort out those needs. This article
Images in Photo
Gallery with Drag and
provides a custom solution for the data dependency between country-state-city
Drop using PHP AJAX inputs. We have done this before for country-state dropdowns.
PHP AJAX
Programming
PHP Star Rating What is inside?
System with JavaScript
Events Display using 1. Existing libraries for creating dependent dropdowns
PHP AJAX with CLNDR
Calendar Plugin 2. About Country-State-City example
RESTful API 3. Country-State-City example file structure
PHP Databases 4. Dependent dropdown HTML
PHP Sessions and 5. jQuery AJAX script to fetch dependent data
Cookies 6. PHP code to fetch the country’s states and state’s cities
Error and Exception 7. Country State City SQL script
Handling
8. Country State City dependent dropdown example output
File Upload
Files and Directories
PHP Date Time Existing libraries for creating dependent
PHP XML
dropdowns
PHP Code Samples
Library There are many plugins available in the market for creating dependent
More PHP dropdowns. Let us see a couple of those plugins in this section.
https://phppot.com/php/country-state-city-example-cascading-jquery-dependent-dropdown/ 1/8
04/01/2021 Country-State-City Example: Cascading jQuery AJAX Dependent Dropdown in PHP - Phppot
PHP Freelancer Dynamic jQuery Cascading Dropdown Lists Plugin is a jQuery plugin. It provides
Basic/Dynamic mode of dependent dropdowns variations. It supports to load
both static or dynamic data.

Dynamic Cascading Dropdown For Bootstrap – Cascader is a jQuery based


Bootstrap plugin. It helps to render sub-dropdowns in a hierarchical order.

About Country-State-City example


The dependent dropdown feature is relevant for a group of related dropdowns
elements. This example has a HTML form with country, state, city dropdown. I
will explain how to make them as dependent dropdowns.

These dropdown options are from the database. Instead of getting all the
options, let us fetch data on a need basis for the dependent dropdown.

This type of dynamic loading will give relevant data based on user selection.
Also, it will reduce the user effort to search for a suitable option.

In a PHP jQuery example, we have seen already how to load dynamic


options for a select box.

I used jQuery AJAX with PHP to load data for the dependent dropdowns. The
country dropdown will show all its options on page load. On its change event, I
invoke AJAX to get dependent results for the state dropdown.

As same as the country-state dependent data load, the state-city will work.
There are separate AJAX handlers and endpoints to get the dependent state
and city.

Country-State-City example file structure

Dependent Dropdown HTML


This code is to display the country state city dependent dropdowns to the user.

It includes PHP code to load the initial options for the country dropdown. The
PHP code connects the database and retrieves the country result in an array
format.

Each dropdown field’s change event invokes jQuery method to get the
dependent data. The jQuery method requests PHP for the dependent data via

https://phppot.com/php/country-state-city-example-cascading-jquery-dependent-dropdown/ 2/8
04/01/2021 Country-State-City Example: Cascading jQuery AJAX Dependent Dropdown in PHP - Phppot
AJAX.

This HTML code has the dependent dropdown as a target container. In this
HTML target, the AJAX response loads the dependent data dynamically.

In a previous article, we have seen how to show dependent dropdown options


with multi-select. It increases the search criteria and retrieves more data for the
select box options.

<?php
namespace Phppot;

use Phppot\CountryState;
require_once __DIR__ . '/Model/CountryStateCity.php';
$countryStateCity = new CountryStateCity();
$countryResult = $countryStateCity->getAllCountry();
?>
<html>
<head>
<TITLE>jQuery Dependent DropDown List - Countries and States</TITLE>
<head>
<link href="./assets/css/style.css" rel="stylesheet" type="text/css" />
<script src="./vendor/jquery/jquery-3.2.1.min.js" type="text/javascript
<script src="./assets/js/ajax-handler.js" type="text/javascript"></scri
</head>
<body>
<div class="frmDronpDown">
<div class="row">
<label>Country:</label><br /> <select name="country"
id="country-list" class="demoInputBox"
onChange="getState(this.value);">
<option value disabled selected>Select Country</option>
<?php
foreach ($countryResult as $country) {
?>

jQuery AJAX Script to Fetch Dependent Data


AJAX is not mandatory to implement a dependent dropdown in an application.
We can also submit the form with selected data to get the dependent data result.

But, it will give a good user experience with AJAX compared to the form submit.
We have to ensure about the importance of using AJAX before coding it.
Because unnecessary AJAX usage is an overload for an application.

In this example, I have used a simple AJAX code in jQuery. You can see the
JavaScript methods getState(), getCity() in the below code. It has the AJAX
script to get the dependent data from the server-side.

These methods call appropriate PHP files for the dependent dropdown results.
These results are from the database retrieved using PHP MySQL.

This is the getState() method definition. It sends selected country id to the get-
state-ep.php endpoint.

function getState(val) {
$.ajax({
type: "POST",
url: "./ajax/get-state-ep.php",
data:'country_id='+val,
beforeSend: function() {
$("#state-list").addClass("loader");
},
success: function(data){
$("#state-list").html(data);
$('#city-list').find('option[value]').remove();
$("#state-list").removeClass("loader");
}
});
}

This JavaScript method is like the getState method we have seen above. It
passed the state id to the get-city-ep.php to get the city option in a HTML format.

On changing the state dropdown values, this method executes the jQuery AJAX
script.

function getCity(val) {
$.ajax({
type: "POST",
url: "./ajax/get-city-ep.php",
data:'state_id='+val,
beforeSend: function() {
$("#city-list").addClass("loader");
},
success: function(data){

https://phppot.com/php/country-state-city-example-cascading-jquery-dependent-dropdown/ 3/8
04/01/2021 Country-State-City Example: Cascading jQuery AJAX Dependent Dropdown in PHP - Phppot
$("#city-list").html(data);
$("#city-list").removeClass("loader");
}
});
}

The success callback handles the response returned from the server-side.

The jQuery code inside the success callback method handles the AJAX
response. It updates the dependent dropdown options as it is from the PHP in a
HTML format.

PHP Code to Fetch Country’s States and State’s


Cities
I have created two PHP programs get-state-ep.php and get-city-ep.php.

I call get-state-ep.php via AJAX by sending the selected country. This PHP code
will fetch the state result based on the selected country from the database.

In get-city-ep.php I received the state id parameter posted via AJAX. The


SELECT query in the following code uses the parameter to fetch cities based on
it.

The PHP code to execute the database fetch is running on a conditional basis.
In that condition, it checks if the country or state id passed via AJAX is not
empty.

It returns group HTML <option></option> tags as a response to update the


dependent dropdown. We can also return JSON response and handle it on the
client-side.

get-state-ep.php

<?php
namespace Phppot;

use Phppot\CountryState;
if (! empty($_POST["country_id"])) {

$countryId = $_POST["country_id"];

require_once __DIR__ . '/../Model/CountryStateCity.php';


$countryStateCity = new CountryStateCity();
$stateResult = $countryStateCity->getStateByCountrId($countryId);
?>
<option value="">Select State</option>
<?php
foreach ($stateResult as $state) {
?>
<option value="<?php echo $state["id"]; ?>"><?php echo $state["name"]; ?>
<?php
}
}
?>

get-city-ep.php

<?php
namespace Phppot;

use Phppot\CountryState;
if (! empty($_POST["state_id"])) {

$stateId = $_POST["state_id"];

require_once __DIR__ . '/../Model/CountryStateCity.php';


$countryStateCity = new CountryStateCity();
$cityResult = $countryStateCity->getCityByStateId($stateId);
?>
<option>Select City</option>
<?php
foreach ($cityResult as $city) {
?>
<option value="<?php echo $city["id"]; ?>"><?php echo $city["name"]; ?><
<?php
}
}
?>

CountryStateCity.php

<?php
namespace Phppot;

use Phppot\DataSource;

https://phppot.com/php/country-state-city-example-cascading-jquery-dependent-dropdown/ 4/8
04/01/2021 Country-State-City Example: Cascading jQuery AJAX Dependent Dropdown in PHP - Phppot

class CountryStateCity
{
private $ds;

function __construct()
{
require_once __DIR__ . './../lib/DataSource.php';
$this->ds = new DataSource();
}

/**
* to get the country record set
*
* @return array result record
*/
public function getAllCountry()
{
$query = "SELECT * FROM country";
$result = $this->ds->select($query);
return $result;
}

Country State City SQL Script


This SQL script contains the structure and the data dump for the country, state
and city tables.

It also shows the ALTER queries for adding the required indexes and
constraints.

Import this script in your environment while setting this example in local. The
sample data given in the SQL is dependent on each other. It will help to make
the example work by getting expected dependent results.

--
-- Table structure for table `city`
--

CREATE TABLE `city` (


`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`state_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `city`
--

INSERT INTO `city` (`id`, `name`, `state_id`) VALUES


(1, 'Diadema', 1),
(2, 'Mauá', 1),
(3, 'Rio Grande da Serra', 1),
(4, 'Angra dos Reis', 2),
(5, 'Barra Mansa', 2),
(6, 'Belford Roxo', 2),
(7, 'Cabo Frio', 2),
(8, 'Aquiraz', 3),
(9, 'Canindé', 3),
(10, 'Caucaia', 3),
(11, 'Crato', 3),

Country State City relationship with ERD

This ERD shows the entity relationship between the country, states, city
database tables.

It will explain the interdependency between the entities taken for this example.

https://phppot.com/php/country-state-city-example-cascading-jquery-dependent-dropdown/ 5/8
04/01/2021 Country-State-City Example: Cascading jQuery AJAX Dependent Dropdown in PHP - Phppot

Country State City Dependent Dropdown Output


The below screenshot shows the dependent dropdown example output.

We can see the inter-dependancy between the selected option shown in this
screenshot.

On choosing the USA for the country dropdown, it shows the corresponding
states. When we select a state of California from the options, then it populates
the dependent cities.

So, each entity depends on its parent to display the related result from the
database.

Conclusion
We have enhanced the dependent dropdown code by adding one more
dropdown to the cascade. The cascading dropdowns behave based on their
parent selection.

With or without AJAX which doesn’t matter while creating dependent dropdown.
But, this code will give the best model to provide a good user experience with
AJAX.

By enabling multi-select for these dropdowns helps to widen the dependent data
search. I herewith interlinked the other dependent dropdowns code from
previous articles.

I hope this example code and the related interlinks added in this article will help
you.

view demo download

Comments to “Country-State-City Example:


Cascading jQuery AJAX Dependent Dropdown in
PHP”

arman
August 24, 2019 at 8:14 pm

hello.
very & very good,
thanks

https://phppot.com/php/country-state-city-example-cascading-jquery-dependent-dropdown/ 6/8
04/01/2021 Country-State-City Example: Cascading jQuery AJAX Dependent Dropdown in PHP - Phppot

Reply

Vincy
June 25, 2020 at 12:36 pm

Thank you Arman.

Reply

nn
December 5, 2019 at 10:47 am

tq…. soo much.

Reply

Vincy
December 5, 2019 at 4:19 pm

Welcome :-)

Reply

Aslal Shaja
January 22, 2020 at 9:14 am

I was very helpful my project thank you so mush

Reply

Vincy
January 23, 2020 at 1:57 pm

Welcome Aslal :-)

Reply

Leave a Reply

Comment

Name *

Email *

Post Comment

Popular Articles
★ PHP AJAX Programming
★ Create AJAX-Based PHP Event Management System with Bootstrap
★ PHP Star Rating System with JavaScript

https://phppot.com/php/country-state-city-example-cascading-jquery-dependent-dropdown/ 7/8
04/01/2021 Country-State-City Example: Cascading jQuery AJAX Dependent Dropdown in PHP - Phppot
Search articles

↑ Back to Top

Looking for a freelance web developer?


Do you want to build a modern, lightweight, responsive website and launch quickly? Contact Me

Blog subscription:

Enter your email here Subscribe

Shop

FAQ Support Policy Refund Policy Licenses


Terms of Service Privacy Policy Cookie Policy © 2020 Phppot

https://phppot.com/php/country-state-city-example-cascading-jquery-dependent-dropdown/ 8/8

You might also like