Dependant Drop Downs Using Ajax
May 12, 2010 in Ajax/JavaScript by Alan Holmes

Dependant Drop Downs Using Ajax

1 Star2 Stars3 Stars4 Stars5 Stars
No Ratings Yet
Loading ... Loading ...

This tutorial will explain how to create dependant/cascading drop down menus, using Ajax to retrieve the options for the sub menus.

About the Author: Alan Holmes

Hi I'm Alan Holmes, the owner of AHdevelopment. I have been doing web development for many years, and I created this site so that I can finally start archiving my development solutions in one central place, as well as making them available for others to find.

Alan Holmes has written 8 article(s).

The Idea

Probably one of the most common needs for drop down menus (select menus), is to have multiple depending drop downs, an example of this could be cars, having makes and models. The requirement, is that when a user selects a value in the first drop down, the second drop down is then filled with corresponding data.

In the past, this was solved by submitting the page on each selection, and although this solves the problem quite well, it is far from ideal. With this method the whole page would have to be loaded every time the user selects a value (specifically if the data is to be retrieved from a database), not only meaning a slower experience for the user (and possibly a higher server usage), but also extra coding would be needed to ensure the rest of the users entries are remembered (enough though that is already likely to be in place for server side validation).

With the usage of JavaScript becoming more common, and the arrival of Ajax (asynchronous JavaScript and XML), comes a far better solution, and certainly a more user friendly solution. Using Ajax, we can send a request to the server to get the data, and then display in the in second drop down menu, without the user seeing anything happening.

The Solution

In this tutorial, we will be creating a demo that will use car make and models to illustrate the use of Ajax to meet these needs, you can view a demo here.

The Form

Firstly, lets create the form, with the needed. For this sample, we will be using just a few cars and models for each, that will not be retrieved from the database (though it can simply be altered to make so).

As you can see, only the Make menu has any values, the Model will be filled upon selection of a Make.

<form>
	<select id="CarMake" name="CarMake" onchange="GetModels();">
		<option value=""> -- Please Select -- </option>
		<option value="Audi">Audi</option>
		<option value="BMW">BMW</option>
		<option value="Ford">Ford</option>
	</select>
	<select id="CarModel" name="CarModel">
		<option value=""> -- Please Select -- </option>
	</select>
</form>

The Ajax

That’s the easy part done with, now onto the Ajax. Firstly we need to create the XmlHttpRequest Object that will be used to retrieve the data.

//Our XmlHttpRequest object to get the models
var xmlModels = getXmlHttpRequestObject();

//Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject() {
	if (window.XMLHttpRequest) {
		return new XMLHttpRequest();
	}else if(window.ActiveXObject) {
		return new ActiveXObject("Microsoft.XMLHTTP");
	}
}

Now we will create the GetModels that is called when a change is made to the Car Make drop down. This function will get the current selected value of the Car Make drop down, and then make a call to an ASP page, which will process the make and return the relevant models.

function GetModels(){

	//Get the Car Make
	sltCarMake = document.getElementById("CarMake");
	strCarMake = sltCarMake.options[sltCarMake.selectedIndex].value;

	//URL to get the models from, the timestamp is to ensure that
	//each request is fresh, and not cached
	//(especially if data is from the database)
	var timestamp = Number(new Date());
	var url='models.asp?Make=' + strCarMake + '&ts=' + timestamp

	//The Ajax Request, the response is handled in the function Models_Handle
	xmlModels.open("GET", url, true);
	xmlModels.onreadystatechange = Models_Handle;
	xmlModels.send(null);
}

Now that we have the data, we need to process it, and that is done by the Models_Handle function, which is take the data, and split it into an array, which is then entered into the drop down menu.

function Models_Handle(){
	if (xmlModels.readyState == 4) {
		//Get the Response
		var strResponse = xmlModels.responseText

		//Car Model object
		sltCarModel = document.getElementById("CarModel");

		//reset select menu to default
		sltCarModel.options.length=0;
		sltCarModel.options[0] = new Option(" -- Please Select -- ","");

		if (strResponse != ""){

			//Split response into array
			var arrResponse = strResponse.split("||");	

			var arrLen = arrResponse.length;
			var intPos = 0;
			for(i=0;i<arrLen;i++){
				sltCarModel.options[i + 1] = new Option(arrResponse[i],arrResponse[i]);
			}
		}
	}
}

The ASP Page

All that is left to create is the ASP page to return the data. In this sample we will be using some hard coded values, but you can simply replace this with some database driven code to output the same results.

strCarMake = request("Make")
strCarModels = ""

select case lcase(strCarMake)

	case "audi"
		strCarModels = "A1||A2||A3||A4||A5"
	case "bmw"
		strCarModels = "Series 1||Series 3||Series 5||Series 6||Series 7"
	case "ford"
		strCarModels = "Ka||Fiesta||Focus||Focus RS||Mondeo"

end select

response.Write(strCarModels)

Compatibility, Conclusion and Download

This script has been tested in IE7 (though should also work in IE6), Firefox 3.5.3, Google Chrome 4.1.2 and Safari 4.0.5, all on a windows platform. This is a very useful technique, which can easily be altered to fill several dependant drop downs. The Ajax technique can also be used retrieve data for other form elements, and to get ‘dynamic’ content for web pages.

Any feedback or improvements are welcome.

Leave a Reply

Can't find what your looking for?? Try Searching