<

Using a drop down box to populate a second drop down box

Published on
5,771 Points
2,171 Views
1 Endorsement
Last Modified:
I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX.

The logical flow for the problem should be:
  1. Write an event handler for the first drop down box to get the user's selections.
  2. Send the user input to the server
  3. At the server, retrieve the data from the client side and process it; then send the result to client side.
  4. At the client, use Javascript to parse the server response and update the other drop down box.


Write an event handler for the first drop down box to get the user's selections:

It sounds difficult. What is an "event handler"?  In fact, every user action performed on the web page triggers an event. To handle those events, we need to write a Javascript function, and we call these javascript functions "event handlers". To handle the user's selection of an item in drop-down box, we need to capture the onchange event. Here is a sample code:
 
 <select id=type name="type" onchange="updateData(this)">

Open in new window


The above code means that a function named "updateData" would be triggered when user selects an item from this drop down box. Here the variable "this" means the dropdown box itself. Let's see what happens in the "updateData" function:
function updateData(dropDownBox)
{
  var value=dropDownBox.options[dropDownBox.selectedIndex].value;
  if (value!="") //Ensure no empty value is submitted to server side
  {
    jQuery.post("getResult.php","type="+value,updateNumber);
  }
}

Open in new window


Send the user input to the server

The statement:

var value=dropDownBox.options[dropDownBox.selectedIndex].value;

Open in new window

retrieves user input from the first drop down box. The following statement mean user input is sent to server side php script "getResult.php".
 
jQuery.post("getResult.php","type="+value,updateNumber);

Open in new window

where, we use the Jquery lib to simplify the sending data to server process. The second parameter is the format of a normal query string and the third parameter is a function that processes the server response.
 

At the server, retrieve the data from the client side and process it; then send the result to client side:

The server side program in our case is "getResult.php". For demonstration purposes we do not connect to a database; we just use the user input to generate a different result and then send that to client.

<?php
	$type=htmlspecialchars($_POST["type"]);
	if ($type=="1")
	{
		echo "1-one\n";//Ends-with \n for client side getting data from server side response
		echo "3-three\n";//Ends-with \n for client side getting data from server side response
		echo "5-five\n";//Ends-with \n for client side getting data from server side response
		echo "7-seven\n";//Ends-with \n for client side getting data from server side response
	}
	else
	{
		if ($type=="0")
		{	echo "2-two\n";//Ends-with \n for client side getting data from server side response
			echo "4-four\n";//Ends-with \n for client side getting data from server side response
			echo "6-six\n";//Ends-with \n for client side getting data from server side response
			echo "8-eight\n";//Ends-with \n for client side getting data from server side response
		}
	}		
?>

Open in new window


At the client, use Javascript to parse the server response and update the other drop down box.

As described above, we need to specify a function that processes the server response and updates the other drop down box.
 
jQuery.post("getResult.php","type="+value,updateNumber);

Open in new window


So, we need to write a Javascript function named "updateNumber" to get the job done.
function updateNumber(data)
      {
        var numberData=jQuery.trim(data).split("\n");//split server side response by "\n"
        var number=document.getElementById("number");
        $("#number").empty();                       //empty the 2nd drop down box  
        for (i=0;i<numberData.length;i++)
        {
          value=numberData[i].split("-")[0];//get value from server response 
          text=numberData[i].split("-")[1]; //get text from server response 
          option=new Option(text,value);    //for better IE compatibility
          number.options[i]=option;      
        }
      }

Open in new window

The first two lines of the function parses server response and the third line empties the target drop down box; the for loop is adding options to the target drop down box.

I have attached the sample code for your reference.
php-ajax.zip
1
Comment
Author:cstsang
0 Comments

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Join & Write a Comment

The viewer will receive an overview of the basics of CSS showing inline styles. In the head tags set up your style tags: (CODE) Reference the nav tag and set your properties.: (CODE) Set the reference for the UL element and styles for it to ensu…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
Suggested Courses
Course of the Month17 days, 11 hours left to enroll

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month