Country-State-City Example - Cascading JQuery AJAX Dependent Dropdown in PHP - Phppot
Country-State-City Example - Cascading JQuery AJAX Dependent Dropdown in PHP - Phppot
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.
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.
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.
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.
<?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) {
?>
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.
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.
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.
get-state-ep.php
<?php
namespace Phppot;
use Phppot\CountryState;
if (! empty($_POST["country_id"])) {
$countryId = $_POST["country_id"];
get-city-ep.php
<?php
namespace Phppot;
use Phppot\CountryState;
if (! empty($_POST["state_id"])) {
$stateId = $_POST["state_id"];
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;
}
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`
--
--
-- Dumping data for table `city`
--
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
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.
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
Reply
nn
December 5, 2019 at 10:47 am
Reply
Vincy
December 5, 2019 at 4:19 pm
Welcome :-)
Reply
Aslal Shaja
January 22, 2020 at 9:14 am
Reply
Vincy
January 23, 2020 at 1:57 pm
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
Blog subscription:
Shop
https://phppot.com/php/country-state-city-example-cascading-jquery-dependent-dropdown/ 8/8