<

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

Published on
6,332 Points
2,732 Views
1 Endorsement
Last Modified:

I found this question 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 the 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 the drop-down box, we need to capture the onchange event. Here is a sample code:

 

 <select id=type name="type" onchange="updateData(this)">


The above code means that a function named "updateData" would be triggered when a 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);
  }
}


Send the user input to the server

The statement:


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

retrieves user input from the first drop down box. The following statement means user input is sent to server side PHP script "getResult.php".

 

jQuery.post("getResult.php","type="+value,updateNumber);

where we use the Jquery lib to simplify the sending data to the 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 the 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 the 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
		}
	}		
?>


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);


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;      
        }
      }

The first two lines of the function parse server response and the third line empty 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
Author:KNVB HK
Ask questions about what you read
If you have a question about something within an article, you can receive help directly from the article author. Experts Exchange article authors are available to answer questions and further the discussion.
Get 7 days free