Let's say I have a table called "address" with a list of addresses in it. Fields include address, city, state.

My HTML form will be a select statement by which the options are populated with the list of distinct states (SELECT DISTINCT state FROM address).

Got that part.

Now I want it to pull a distinct select/option list using the state I just chose in the previous select/option. Seems JavaScript is the way to do this, but I'm pretty rusty at that. I want to return a list of all cities in the table that match the state I just chose.

Ideas? Sample here:

<form action="search.php" method="post" name="resform" id="resform">
State:<select name="state" id="state">
<option value="" selected="selected">Select a State</option>
	<?php
		$stquery = "SELECT DISTINCT state FROM address";
		$stres = mysql_query($stquery) or die(mysql_error());
		while ($strow = mysql_fetch_assoc($stres))
		{
			extract($strow);
			echo "<option value=\"" . $state . "\">" . $state . "</option>";	
		}

?>
</select>
<BR>
<select name="city" id="city">
<!--OPTIONS NEED TO FILL HERE FROM DB -->
</select>

    Here are the steps to accomplishing what you're looking for:

    1. You're going to have an onchange event listener on your state select element.
    2. When it changes, you'll have some JavaScript make an AJAX call to a PHP script (passing the state as an argument).
    3. This PHP script will query the database, selecting all the cities where state equals what you passed it.
    4. The PHP script then echoes out the results.
    5. Your JavaScript AJAX call will then receive the echoed data and present it accordingly (in this case, probably in the form of <option></option> elements).

    I recommend jQuery for the AJAX parts since it simplifies the process for you and makes it much easier.

    Godspeed.

      Write a Reply...