I am really confused. I want to create a Select drop down menu using information from an sql database. everything works out great but i have one question. how do i update the select drop down every time the user changes his selection. the question is really confusing and i dont really know how to describe it.. I set up the code in php and then put it inside my page. here is the code:
<?php
//creating a function to generate the second select menu
function createNameSelect(){
$options = "<select id='name'>"
$sql = "SELECT * FROM names WHERE category = 'c'";
$result = mysql_query($sql);
$options.="<option value='nothing'>-- select an option --</option>";
while ($row=mysql_fetch_array($result)){
$name=$row['name'];
$options.="<option value='$name'>$name</option>";
}
$options.="</select>";
return "$options";
}
?>
<!DOCTYPE html>
....
<select id = c>
<option value ='1'>option 1</option>
<option value ='2'>option 2</option>
<option value ='3'>option 3</option>
</select>
<?php createNameSelect(); ?>
....
</html>
now, it works perfect, however, it won’t update the select menu that follows the first one.
it would be stuck on the menu generated from the default option.
any idea what i can do to fix it? is there a js solution to it?
Thanks!
PHP is a server side script – it will be executed precisely once on the server, and the output will be sent to the client (viewer browser). So you can’t call that PHP function over and over again as the user changes the first select.
What you need to do is make a separate PHP file that, when given a valid option for the first select, prints out code for the second select. Then you use AJAX to invoke that PHP file using the jQuery .get() function, and replace the contents of the second select with the results you get.