Populating the state or city dropdown based on the value of option selected by the user in the country dropdown is a very common implementation of Ajax feature that you have seen on many websites while filling the registration form. You can do this easily through the jQuery ajax() method along with the little help of any server side scripting language like PHP.
Let's take a look at the following example to understand how it basically works:
The jQuery script above send the value of option selected in the country dropdown to the server. The "process-request.php" file on the server then process the request, if the request succeeds the jQuery script receives the returned data and creates the city dropdown list.
The PHP code inside the "process-request.php" file will look something like this:
<?php
if(isset($_POST["country"])){
// Capture selected country
$country = $_POST["country"];
// Define country and city array
$countryArr = array(
"usa" => array("New Yourk", "Los Angeles", "California"),
"india" => array("Mumbai", "New Delhi", "Bangalore"),
"uk" => array("London", "Manchester", "Liverpool")
);
// Display city dropdown based on country name
if($country !== 'Select'){
echo "<label>City:</label>";
echo "<select>";
foreach($countryArr[$country] as $value){
echo "<option>". $value . "</option>";
}
echo "</select>";
}
}
?>
We have created a simple PHP array to store country and city records for demo purpose. However, in real world scenario you need to store these records in database. Please check out the PHP and MySQL tutorial section to learn about inserting and retrieving records from database.
Use the jQuery
ajax()methodPopulating the state or city dropdown based on the value of option selected by the user in the country dropdown is a very common implementation of Ajax feature that you have seen on many websites while filling the registration form. You can do this easily through the jQuery
ajax()method along with the little help of any server side scripting language like PHP.Let's take a look at the following example to understand how it basically works:
The jQuery script above send the value of option selected in the country dropdown to the server. The "process-request.php" file on the server then process the request, if the request succeeds the jQuery script receives the returned data and creates the city dropdown list.
The PHP code inside the "process-request.php" file will look something like this:
We have created a simple PHP array to store country and city records for demo purpose. However, in real world scenario you need to store these records in database. Please check out the PHP and MySQL tutorial section to learn about inserting and retrieving records from database.
need an explanation for this answer? contact us directly to get an explanation for this answer