TheRealDK
TheRealDK

Reputation: 367

Can not get value for Select item?

I can't seem to get the value for a 'selected item' to pass to a JavaScript function with PHP that uses the value to query data from MySQL database -> populates a different drop down list.

Here is my 'HTML' code

<select name="numbers" id="numbers" onChange="populateOtherSelect()">
   <option value="one">one</option>
   <option value="two">two</option>
   <option value="three">three</option>
   <option value="four">four</option>
</select>

<?php echo $option ?>

Here is my 'JavaScript' function code

function populateOtherSelect() {
 <?php
   // code that opens db connection

   $numbers = $_POST['numbers']; 

   $query = "select*from Database.Table where Something = 'Something' and Numbers like '%".$numbers."%'";

   $result = mysql_query($query);

   $option = "";

   while($row = mysql_fetch_array($result))
    {
        $OtherOptions = $row["OtherOptions"];
        $option.="<option value=\"$OtherOptions\">".$OtherOptions."</option>\r\n";
    }

   // code that closes db connection
?>

}

Any information will be helpful.

Thanks very much

Upvotes: 0

Views: 176

Answers (3)

jeroen
jeroen

Reputation: 91742

It seems your javascript code is part of the html / php document and that´s not going to work; the php is run only at initial page-load and at that moment there probably is no $_POST variable.

What you need to do, is make an ajax call to a php script at the moment your first select is changed and use the response from that ajax call to populate your second select.

So basically your javascript function would have to look like:

function populateOtherSelect() {
  /*
   * 1. get the value of the numbers select
   * 2. make an ajax call to a php script / the server that gets some information from a database
   * 3. use the response from the ajax call to populate your second select
   */
}

Upvotes: 2

joakimdahlstrom
joakimdahlstrom

Reputation: 1595

First of all, the $Numbers variable doesn't exist, it's $numbers.

Upvotes: 0

Dirk
Dirk

Reputation: 3093

I think you need to add a space in your select statement:

$query = "select * from Database.Table where Something = 'Something' and Numbers like '%".$Numbers."%'";

Upvotes: 0

Related Questions