Everyone answered that Ajax is the solution, and I agree, Ajax is more elegant, but Ajax is not the only solution. I post this answer only to show another way to do it : without Ajax.
The first code (combos.php) is the page with a combo that, when selected, calls PHP. The second code (combos_action.php) is the PHP that returns the values according to the option selected. To make this codes to work, create two text files with the given names, copy-paste the codes and run it from your browser with http://localhost/combos.php
. If you change the filenames, change them in the code, also.
Here is how it works : the page shows a simple combo filled with the days of the week. When a day is selected the JavaScript's onchange
event fires and the form is autosubmitted, PHP gets the selected day and stores some values in session, returns to the page that refreshes and fills the second combo with those values. Comments will help you to understand:
combos.php
<?php
session_start(); // NECESSARY TO RETRIEVE THE VALUE RETURNED FROM PHP.
?>
<html>
<head>
<title>By José Manuel Abarca Rodríguez</title>
<script type="text/javascript">
// AUTOSUBMIT FORM #1 WHEN ANY OPTION IN COMBO #1 IS SELECTED.
function combo1_selected () {
document.getElementById( "form1" ).submit();
}
</script>
</head>
<body>
<!-- THIS IS COMBO #1. -->
<form id="form1" method="post" action="combos_action.php">
Select a day
<br/>
<select name="combo1" onchange="combo1_selected()"> <!-- NOTICE THE EVENT! -->
<option>Monday</option>
<option>Tuesday</option>
<option>Wednesday</option>
</select>
</form>
<?php
// DISPLAY COMBO #2 ONLY IF COMBO #1 WAS SELECTED.
if ( isset( $_SESSION[ "combo2" ] ) )
{ echo "<br/>" .
"<br/>" .
"Options for <b>" . $_SESSION[ "combo1" ] . "</b>" .
"<br/>" .
"<select name='combo2'>";
// SEPARATE THE OPTIONS RETURNED FROM PHP.
$options = explode( ",",$_SESSION[ "combo2" ] );
// DISPLAY THE OPTIONS FOR THE COMBO.
for ( $i = 0; $i < count( $options ); $i++ )
echo "<option>" . $options[ $i ] . "</option>";
echo "</select>";
}
?>
</body>
</html>
combos_action.php
<?php
session_start();
$_SESSION[ "combo1" ] = $_POST[ "combo1" ]; // SELECTED OPTION.
if ( $_SESSION[ "combo1" ] == "Monday" )
$_SESSION[ "combo2" ] = "mon 1,mon 2,mon 3"; // RETURN THESE VALUES.
if ( $_SESSION[ "combo1" ] == "Tuesday" )
$_SESSION[ "combo2" ] = "tue 1,tue 2,tue 3"; // RETURN THESE VALUES.
if ( $_SESSION[ "combo1" ] == "Wednesday" )
$_SESSION[ "combo2" ] = "wed 1,wed 2,wed 3"; // RETURN THESE VALUES.
header( "Location: combos.php" ); // RETURN TO PAGE.
?>