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="http://code.jquery.com/jquery.js"></script>

Html view:

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

</div>

Step 2: Call jQuery change event and fetch the ajax

<script type="text/javascript">
$(document).ready(function(){
    $("select.country").change(function(){
        var selectedCountry = $(".country option:selected").val();
        $.ajax({
            type: "POST",
            url: "<?php echo $this->Html->Url(array('action'=>'processRequest'));?>",
            data: { country : selectedCountry }
        }).done(function(data){
            $("#response").html(data);
        });
    });
});

</script>

Step 3: processRequest action in controller

function processRequest(){
      if(isset($_POST["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>";
}
         }
}

No comments:

Post a Comment

Bottom Ad [Post Page]