Multiple Select Dropdown List with AJAX

This tutorial presents an AJAX script that can be used to create dynamically multiple Select lists with data from a MySQL table.

First, a single select list is displayed on the page, then when the user chooses an option, it calls an Ajax function that acceses a PHP file that will return a select list according to the option selected. The Ajax function receives and displays the second select list.
When the users selects an option from the second select list, this script can display a third list of options, according to the options selected in the first an second select lists.

The script contains two files, a PHP file (named "select_list.php") with the code that selects data from a MySQL table and returns a select drop down list, and a JS file (named "ajax_select.js") with the Ajax code that accesses the PHP file.
You can copy and use the code for these files displayed below, or download the files from: Script Multiple Select Dropdown List

On this page: Multiple Drop-Down Select Lists Creator it is another Ajax script, with Administration Page, that can be used to create multiple select lists.


The code for select_list.php

<?php
// Multiple select lists - http://coursesweb.net/ajax/
if(!isset($_SESSION)) session_start();

// Here add your own data for connecting to MySQL database
$server = 'localhost';
$user = 'username';
$pass = 'password';
$dbase = 'dbname';

// Here add the name of the table and columns that will be used for select lists, in their order
// Add null for 'col_description' if you don`t want to display their data too
$table = 'table_name';
$ar_cols = array('col_select1', 'col_select2', 'col_select3', 'col_description');

$preid = 'slo_';        // a prefix used for element's ID, in which Ajax will add <select>
$col = $ar_cols[0];     // the variable used for the column that wil be selected
$re_html = '';          // will store the returned html code

// if there is data sent via POST, with index 'col' and 'wval'
if(isset($_POST['col']) && isset($_POST['wval'])) {
  // set the $col that will be selected and the value for WHERE (delete tags and external spaces in $_POST)
  $col = trim(strip_tags($_POST['col']));
  $wval = "'".trim(strip_tags($_POST['wval']))."'";
}

$key = array_search($col, $ar_cols);            // get the key associated with the value of $col in $ar_cols
$wcol = $key===0 ? $col : $ar_cols[$key-1];     // gets the column for the WHERE clause
$_SESSION['ar_cols'][$wcol] = isset($wval) ? $wval : $wcol;    // store in SESSION the column and its value for WHERE
  
// gets the next element in $ar_cols (needed in the onchange() function in <select> tag)
$last_key = count($ar_cols)-1;
$next_col = $key<$last_key ? $ar_cols[$key+1] : '';

$conn = new mysqli($server, $user, $pass, $dbase);     // connect to the MySQL database

if (mysqli_connect_errno()) { exit('Connect failed: '. mysqli_connect_error()); }     // check connection

// sets an array with data of the WHERE condition (column=value) for SELECT query
for($i=1; $i<=$key; $i++) {
  $ar_where[] = '`'.$ar_cols[$i-1].'`='.$_SESSION['ar_cols'][$ar_cols[$i-1]];
}

// define a string with the WHERE condition, and then the SELECT query
$where = isset($ar_where) ? ' WHERE '. implode($ar_where, ' AND ') : '';
$sql = "SELECT DISTINCT `$col` FROM `$table`".$where;

$result = $conn->query($sql);       // perform the query and store the result

// if the $result contains at least one row
if ($result->num_rows > 0) {
  // sets the "onchange" event, which is added in <select> tag
  $onchg = $next_col!==null ? " onchange=\"ajaxReq('$next_col', this.value);\"" : '';

  // sets the select tag list (and the first <option>), if it's not the last column
  if($col!=$ar_cols[$last_key]) $re_html = $col. ': <select name="'. $col. '"'. $onchg. '><option>- - -</option>';

  while($row = $result->fetch_assoc()) {
    // if its the last column, reurns its data, else, adds data in OPTION tags
    if($col==$ar_cols[$last_key]) $re_html .= '<br/>'. $row[$col];
    else $re_html .= '<option value="'. $row[$col]. '">'. $row[$col]. '</option>';
  }

  if($col!=$ar_cols[$last_key]) $re_html .= '</select> ';        // ends the Select list
}
else { $re_html = '0 results'; }

$conn->close();

// if the selected column, $col, is the first column in $ar_cols
if($col==$ar_cols[0]) {
  // adds html code with SPAN (or DIV for last item) where Ajax will add the select dropdown lists
  // with ID in each SPAN, according to the columns added in $ar_cols
  for($i=1; $i<count($ar_cols); $i++) {
    if($ar_cols[$i]===null) continue;
    if($i==$last_key) $re_html .= '<div id="'. $preid.$ar_cols[$i]. '"> </div>';
    else $re_html .= '<span id="'. $preid.$ar_cols[$i]. '"> </span>';
  }

  // adds the columns in JS (used in removeLists() to remove the next displayed lists when makes other selects)
  $re_html .= '<script type="text/javascript">var ar_cols = '.json_encode($ar_cols).'; var preid = "'. $preid. '";</script>';
}
else echo $re_html;
?>

The code for ajax_select.js

// Multiple select lists - http://coursesweb.net/ajax/

// function used to remove the next lists already displayed when it chooses other options
function removeLists(colid) {
  var z = 0;
  // removes data in elements with the id stored in the "ar_cols" variable
  // starting with the element with the id value passed in colid
  for(var i=1; i<ar_cols.length; i++) {
    if(ar_cols[i]==null) continue;
    if(ar_cols[i]==colid) z = 1;
    if(z==1) document.getElementById(preid+ar_cols[i]).innerHTML = '';
  }
}

// create the XMLHttpRequest object, according browser
function get_XmlHttp() {
  // create the variable that will contain the instance of the XMLHttpRequest object (initially with null value)
  var xmlHttp = null;

  if(window.XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); }     // for Forefox, IE7+, Opera, Safari
  else if(window.ActiveXObject) { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); }      // IE5 or 6

  return xmlHttp;
}

// sends data to a php file, via POST, and displays the received answer
function ajaxReq(col, wval) {
  removeLists(col);           // removes the already next selects displayed

  // if the value of wval is not '- - -' and '' (the first option)
  if(wval!='- - -' && wval!='') {
    var request =  get_XmlHttp();		      // call the function with the XMLHttpRequest instance
    var php_file = 'select_list.php';     // path and name of the php file

    // create pairs index=value with data that must be sent to server
    var  data_send = 'col='+col+'&wval='+wval;

    request.open("POST", php_file, true);			// set the request

    document.getElementById(preid+col).innerHTML = 'Loadding...';   // display a loading notification

    // adds a header to tell the PHP script to recognize the data as is sent via POST
    request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    request.send(data_send);	      	// calls the send() method with data_send

    // Check request status
    // If the response is received completely, will be added into the tag with id value of "col"
    request.onreadystatechange = function() {
      if (request.readyState==4) {
        document.getElementById(preid+col).innerHTML = request.responseText;
      }
    }
  }
}

Usage Script Multiple Select Drop down List

1) Create the files: "select_list.php" and "ajax_select.js" on your server (with the code presented above), in the same directory.
In the PHP script, add your own data for connecting to MySQL, the table name (in $table) and the name of the columns with data for each Select list (in the array $ar_cols).

- For example, if you have a table named "cities", and you want to create a triple select drop down list with data stored in the columns: "state", "city", and "villages"; then to display some descriptions about each village stored in another column named "villdata", change the value of the $table and $ar_cols variables like this:
// Here add the name of the table and columns that will be used for select lists, in their order
$table = 'cities';
$ar_cols = array('state', 'city', 'villages', 'villdata');
If you want to display only the three select lists (state, city, villages), or you not have a column with description, add null for the last element (in place of 'villdata').

- If you want to create two select drop down list, and then a description for the options of the second Select, add like this:
// Here add the name of the table and columns that will be used for select lists, in their order
$table = 'table_name';
$ar_cols = array('col_select1', 'col_select2', 'col_description');
If you want to display only the Select lists associated with "col_select1" and "col_select2", replace 'col_description' with null.

2) In the web page in which you want to display the select lists with Ajax:
- You must include the "select_list.php" file at the beginning of the page, by adding the following php code, before the HTML code, or any output data (this because it uses session_start()):
<?php include 'select_list.php'; ?>

- Include the "ajax_select.js" file in the HEAD section of the HTML code, by adding the following code:
<script src="ajax_select.js" type="text/javascript"></script>

- Then, in the form where you want to display the Select lists, add:
Select: <?php echo $re_html; ?>
Like you can see in the example below, or in the "test.php" file (in the archive downloaded from the link above).

• The PHP script creates the first <select> with the options from the first column added in $ar_cols Array, then creates HTML tags in which Ajax will add the next Select lists. These HTML tags has an unique ID composed by the string added in $preid variable and the name of the column. The $preid is used to be sure that there isn't another element with the same ID on the page.

If you want to include the select drop down lists into a form, and then to send and use the selected options in other PHP script, you can get the selected value using the "name" of each select, which is the same with the column name with the options for that select, added in the $ar_cols variable.
- For example, the first <select> has name="col_select1" (the first value added in the $ar_cols array). To get the selected option of this dropdown list, use in your PHP script: $_POST['col_select1'].
The second Select list has name="col_select2" (the second value added in the $ar_cols array), and so on.


- If you modify something in the instrutions of the PHP script or in the JavaScript functions, without knowing what you do, it's pretty sure the script to not work.

Example Triple Select drop down list

Here's is a concrete example. We have in MySQL a table named "sites" with these columns: id, site, menu, categ, links; having the following records:
idsitemenucateglinks
1MarPlo.netCoursesAjaxwww.marplo.net/ajax/obiectul_xmlhttprequest.html
2MarPlo.netCoursesAjaxwww.marplo.net/ajax/ajax_get_php.html
3MarPlo.netCoursesAjaxwww.marplo.net/ajax/tutoriale_ajax_json.html
4MarPlo.netCoursesJavaScriptwww.marplo.net/javascript/sintaxajs.html
5MarPlo.netCoursesJavaScriptwww.marplo.net/javascript/notiuni_de_baza.html
6MarPlo.netCoursesJavaScriptwww.marplo.net/javascript/getelementbyid.html
7MarPlo.netCoursesEnglishwww.marplo.net/engleza/gramatica
8MarPlo.netCoursesEnglishwww.marplo.net/engleza/exercitii
9MarPlo.netCoursesEnglishwww.marplo.net/engleza/download_carti-programe-audio
10MarPlo.netAnimeSlice of lifewww.marplo.net/anime/h2o_footprints_sand-a
11MarPlo.netAnimeSlice of lifewww.marplo.net/anime/chobits-a
12MarPlo.netAnimeSlice of lifewww.marplo.net/anime/hayate_no_gotoku-a
13MarPlo.netAnimeComedywww.marplo.net/anime/angel_tales-a
14MarPlo.netAnimeComedywww.marplo.net/anime/my_bride_is_a_mermaid-a
15MarPlo.netAnimeComedywww.marplo.net/anime/nodame_cantabile-a
16MarPlo.netAnimeRomanticwww.marplo.net/anime/clannad-a
17MarPlo.netAnimeRomanticwww.marplo.net/anime/bokura_ga_ita-a
18MarPlo.netAnimeRomanticwww.marplo.net/anime/peach_girl-a
19MarPlo.netGamesAdventure-Mysterywww.marplo.net/jocuri/misson_to_mars-j
20MarPlo.netGamesAdventure-Mysterywww.marplo.net/jocuri/prince_of_persia-j
21MarPlo.netGamesAdventure-Mysterywww.marplo.net/jocuri/river_rapid_rampage-j
22MarPlo.netGamesLogic and Intuitionwww.marplo.net/jocuri/bloxorz-j
23MarPlo.netGamesLogic and Intuitionwww.marplo.net/jocuri/flash_chess_3-j
24MarPlo.netGamesLogic and Intuitionwww.marplo.net/jocuri/red_remover-j
25http://coursesweb.netPHP-MySQLLessonshttp://coursesweb.net/php-mysql/writing-php-scripts
26http://coursesweb.netPHP-MySQLLessonshttp://coursesweb.net/php-mysql/arrays
27http://coursesweb.netPHP-MySQLLessonshttp://coursesweb.net/php-mysql/php-mysql-using-mysqli
28http://coursesweb.netPHP-MySQLTutorialshttp://coursesweb.net/php-mysql/file_put_contents-file_get_contents-readfile-file_t
29http://coursesweb.netPHP-MySQLTutorialshttp://coursesweb.net/php-mysql/uploading-multiple-files_t
30CoursesWeb.netPHP-MySQLTutorialshttp://coursesweb.net/php-mysql/count-number-downloads-accesses_t
31http://coursesweb.netJavaScriptLessonshttp://coursesweb.net/javascript/variables-operators
32CoursesWeb.netJavaScriptLessonshttp://coursesweb.net/javascript/document-object-dom
33CoursesWeb.netJavaScriptLessonshttp://coursesweb.net/javascript/javascript-code-php
34CoursesWeb.netJavaScriptTutorialshttp://coursesweb.net/javascript/align-make-same-height_t
35CoursesWeb.netJavaScriptTutorialshttp://coursesweb.net/javascript/check-file-type-before-upload_t
36CoursesWeb.netJavaScriptTutorialshttp://coursesweb.net/javascript/display-simulate-loading-progress-bar_t
37CoursesWeb.netJavaScriptjQueryhttp://coursesweb.net/jquery/jquery-basics
38CoursesWeb.netJavaScriptjQueryhttp://coursesweb.net/jquery/animating-css-properties
39CoursesWeb.netJavaScriptjQueryhttp://coursesweb.net/jquery/drag-drop
40CoursesWeb.netFlash-AS3Flash Lessonshttp://coursesweb.net/flash/simple-flash-animation-save-export
41CoursesWeb.netFlash-AS3Flash Lessonshttp://coursesweb.net/flash/deco-tool
42CoursesWeb.netFlash-AS3Flash Lessonshttp://coursesweb.net/flash/motion-tween-flash-animation
43CoursesWeb.netFlash-AS3ActionScript Lessonshttp://coursesweb.net/actionscript/introduction-actionscript-3
44CoursesWeb.netFlash-AS3ActionScript Lessonshttp://coursesweb.net/actionscript/simple-script-actionscript
45CoursesWeb.netFlash-AS3ActionScript Lessonshttp://coursesweb.net/actionscript/oop-object-oriented-programming
46CoursesWeb.netFlash-AS3Tutorialshttp://coursesweb.net/flash/xml-actionscript-php-script_t
47CoursesWeb.netFlash-AS3Tutorialshttp://coursesweb.net/flash/access-objects-different-timeline_t
48CoursesWeb.netFlash-AS3Tutorialshttp://coursesweb.net/flash/actionscript-change-movieclip-color_t

We create a triple select list with options stored in the columns: "site", "menu", and "categ", then we'll display the data stored in the column "links", associated with the option selected in the last list (categ).
In the "select_list.php" we set the code:
// Here add the name of the table and columns that will be used for select lists, in their order
// Add null for 'links' if you don't want to display their data too
$table = 'sites';
$ar_cols = array('site', 'menu', 'categ', 'links');

The web page that will display the Select lists has the following code:
<?php include 'select_list.php'; ?>
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Triple Select drop down list with Ajax</title>
<script src="ajax_select.js" type="text/javascript"></script>
</head>
<body>

<form action="" method="post">
Select: <?php echo $re_html; ?>
</form>

</body>
</html>

- Here's the result:
Select sites:

Example Double Select Drop down list

Now we create only two select dropdown list, with the options stored in the columns "site", and "menu" (in the same table presented above).
We just need to modify the $ar_cols variable (in "select_list.php"), by adding the elements 'site', 'menu', and null :
// Here add the name of the table and columns that will be used for select lists, in their order
$table = 'sites';
$ar_cols = array('site', 'menu', null);

- In the same web page created in the previous example, will result:
Select sites: