I need to have a form where a person first chooses his state and based upon the chosen state, the second drop down lists all the cities for that state.
I have already written a code which works well in achieving this.
However, the 2nd list is populated only when the user selects the state from the first list and presses the SUBMIT button.
I need the following changes:
1. the city list should be populated , as soon as the user SELECTS his option in the state dropdown.
SUBMIT button should not be required.
2. In the current code, While the city list is populated correctly, the first drop down gets reset to the starting value in the state list. I want it to remain at the user selected state.
Please suggest changes to achieve this.
Here's my code.
Code: Select all
<?php
function database_connect($select_database)
{
$resource_link = mysql_connect("localhost", "root", "");
if (mysql_select_db($select_database, $resource_link)) {
return $resource_link;
} else {
echo "Cannot connect to DB";
return false;
}
}
//function to display state dropdown
function print_state_dropdown($query, $link){
$queried = mysql_query($query, $link);
$menu = '<select name="state">';
while ($result = mysql_fetch_array($queried)) {
$menu .= '<option value="' . $result['state'] . '">' . $result['state'] . '</option>'; }
$menu .= '</select>';
return $menu;
}
echo '<form method="post" action="">';
echo print_state_dropdown("SELECT DISTINCT state FROM pinlist", database_connect("rakta"));
echo '<input type="submit" name="submit" value="submit"/>
</form>';
if (isset($_POST['submit'])) {
$state=$_POST['state'];
/// function to populate city names for a given state
function print_city_dropdown($query, $link){
$queried = mysql_query($query, $link);
$menu = '<select name="city">';
while ($result = mysql_fetch_array($queried)) {
$menu .= '
<option value="' . $result['city'] . '">' . $result['city'] . '</option>';
}
$menu .= '</select>';
return $menu;
}
//Display City Dropdown form
echo '<form method="post" action="">';
echo print_city_dropdown("SELECT DISTINCT city FROM pinlist WHERE state='$state'", database_connect("rakta"));
echo '<input type="submit" name="submit" value="submit"/>
</form>';
}
?>