Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populating a Dropdown list in PHP dynamically

I have a small PHP page which contains two drop down lists

I need to populate the second one according to the result selected in the first drop down list .... is this possible? In other words I need to use the value selected from the first drop down list and use it in the dB query used to populate the second drop down list (but this should be populated upon selection of the first drop down list.

If this is possible any hints please? (you can assume that I am able to populate the first drop down list from the dB)

like image 962
mouthpiec Avatar asked Oct 25 '22 17:10

mouthpiec


2 Answers

Option 1: embed the data for the second select in the document as hidden elements or JS objects. A change event handler on the first select will populate the second select. A List Apart has an example dynamic select page.

Option 2: use AJAX. When the first select changes, make a request to the server for the contents of the second select, then populate it. With a JS library (such as jQuery), this becomes quite easy.

$('select#one').change(
  function (evt) {
    $('select#two').load('/thing/'+this.value);
  }
);

"/thing/<val>" identifies your server side script to generate a list of items based on "<val>" (use the rewrite facilities of your webserver to resolve the URL path to the actual script). You could simply have it always generate <option> elements, but a better design would be to include a way to specify the result format, so it could output the list as <li>, using JSON or some other format.

$('select#one').change(
  function (evt) {
    $('select#two').load('/thing/'+this.value, {fmt: 'option'});
  }
);
like image 189
outis Avatar answered Nov 09 '22 15:11

outis


You will have to use AJAX to send the selection of the first dropdown to the server. You can then query the database and generate the second dropdown and send it back to the user.

like image 29
Josh Curren Avatar answered Nov 09 '22 15:11

Josh Curren