Coding Cheatsheets - Learn web development code and tutorials for Software developers which will helps you in project. Get help on JavaScript, PHP, XML, and more.

Post Page Advertisement [Top]

Populating city Dropdown based on Country Selecting by using jQuery and Ajax.

Step 1: Load the jquery library

<script type="text/javascript" src=""></script>

Html view:

<select class="country">
<option value="usa">United States</option>
<option value="india">India</option>
<option value="uk">United Kingdom</option>
<div id="response">
    <!--Response will be inserted here-->


Step 2: Call jQuery change event and fetch the ajax

<script type="text/javascript">
        var selectedCountry = $(".country option:selected").val();
            type: "POST",
            url: "<?php echo $this->Html->Url(array('action'=>'processRequest'));?>",
            data: { country : selectedCountry }


Step 3: processRequest action in controller

function processRequest(){
$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>";

No comments:

Post a Comment

Bottom Ad [Post Page]