I have a form on my page which contains two select dropdowns. The first one lets the user choose a country, and the second one lets the user choose a city from that country. I would like for the second dropdown options to be filled with cities based on the previously selected country. Currently, I have an onChange event that leads to an AJAX script which populates the cities from an external php file. Here is my code so far:
HTML Form
<form method="post">
<select name="country" onchange="dynamic_Select('city.php', this.value)" />
<option value="#">-Select-</option>
<option value="India">India</option>
<option value="USA">USA</option>
</select>
<div id="txtResult">
<select name="cityList">
<option></option>
</select>
</div>
</form>
AJAX Script in Header (dynamic_Select)
<script>
function dynamic_Select(ajax_page, country) {
$.ajax({
type: "GET",
url: ajax_page,
data: "ch=" + country,
dataType: "text/html", //<--UPDATE: DELETING THIS LINE FIXES EVERYTHING
//<--UPDATE2: DON'T DELETE; REPLACE "test/html" with "html"
success: function(html){ $("#txtResult").html(html); }
});
}
</script>
//I also have a link to the jquery file
<script src="js/jquery.js" type="text/javascript"></script>
External PHP File (city.php)
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
// List of cities for India
if ($_GET['ch'] == 'India') {
?>
<select name="cityList">
<option value="Mumbai">Mumbai</option>
<option value="Delhi">Delhi</option>
<option value="Bangalore">Bangalore</option>
<option value="Patna">Patna</option>
</select>
<?php
}
// List of cities for USA
if ($_GET['ch'] == 'USA') {
?>
<select name="cityList">
<option value="Albama">Albama</option>
<option value="Alaska">Alaska</option>
<option value="Arizona">Arizona</option>
<option value="Florida">Florida</option>
</select>
<?php
}
?>
The above set of code isn’t working, and I can’t figure out why. Two dropdown lists appear on the page (the second one is initially blank), but after choosing a country from the first dropdown the second dropdown remains blank. Any help would be much appreciated!
Change your dataType parameter from “text/html” to “html”.