Multilevel Dynamic drop down from Database Using AJAX in PHP

Today we are going to learn how to make multilevel dynamic drop down from database using AJAX in PHP.

To do it successfully, we will have to create two different files.
One of them is the main file having HTML view and some javascript codes and the onther one which will return ajax values from database.

Suppose, ‘dropdown.php’ is our main file. Keep the first two parts (php and javascript codes) in this file.
Then place the 3rd and last part in another file named ‘ajax_value.php’.
After you are done with this copy & paste business, just run the main file in your localhost.

So, lets start with the HTML view part first.

<?php

/********** Continent Dropdown List **********/
$continents = array("asia", "europe");

$continent = "<select name=\"continent\" id=\"continent\">";
	$continent.= "<option value=\"999\">Select Continent</option>";
	foreach($continents as $val){
		$continent.= "<option value=\"$val\">".ucwords($val)."";
	}
$continent.= "</select>";



/********** Country Dropdown List **********/
$country = "<select name=\"country\" id=\"country\">";
	$country.= "<option value=\"999\"> - - - </option>";
$country.= "</select>";



/********** City Dropdown List **********/
$city = "<select name=\"city\" id=\"city\">";
	$city.= "<option value=\"999\"> - - - </option>";
$city.= "</select>";



$form = "<center>";
$form.= "<h2>Multiple level dynamic dropdown from Database using AJAX in PHP</h2>";
$form.= "<form>";
	$form.= "<table style=\"font-weight:bold; width:auto;\" border=\"0\" cellpadding=\"5\" bgcolor=\"#DBEAF9\">";
		$form.= "<tr height=\"100\"><td colspan=2 id=\"showLoadingImage\"></td></tr>"; //this is optional, you can show a gif waiting image for the user so that s
		$form.= "<tr><td colspan=2><h3>Select your own city...</h3></td></tr>";
		$form.= "<tr><td>Continent</td><td>: $continent</td></tr>";
		$form.= "<tr><td>Country</td><td>: $country</td></tr>";
		$form.= "<tr><td>City</td><td>: $city</td></tr>";
	$form.= "</table>";
$form.= "</form>";
$form.= "</center>";

echo $form;

?>

Here is the AJAX part. Keep this part together in the same file with the upper part.



<script src="jquery.min.js"></script> <!-- use your own path here -->

<script type="text/javascript">
$(document).ready(function(){	
	$("select").live("change", function(){
		var currentId = $(this).attr("id");
		
		if(currentId == "continent"){
			continent_val = $(this).val();
			
			document.getElementById("showLoadingImage").innerHTML = "<img src=\"loading.gif\">";
			
			var send_data = "continent=" + continent_val + "&next_id=" + "country";

			$.ajax({
				type:"POST",
				url: "ajax_value.php",
				data: send_data,
				cache: false,
				success: function(result){
					document.getElementById("country").innerHTML = result;
					document.getElementById("city").innerHTML = "<option> - - - </option>"; //sets the city dropdown list as blank
					document.getElementById("showLoadingImage").innerHTML = ""; //removes the loading image
				}
			});
		}
		
		else if(currentId == "country"){
			country_val = $(this).val();
			
			document.getElementById("showLoadingImage").innerHTML = "<img src=\"loading.gif\">";
			
			var send_data = "country=" + country_val + "&next_id=" + "city";

			$.ajax({
				type:"POST",
				url: "ajax_value.php",
				data: send_data,
				cache: false,
				success: function(result){
					document.getElementById("city").innerHTML = result;
					document.getElementById("showLoadingImage").innerHTML = ""; //removes the loading image
				}
			});
		}
	});
})

</script>

We are almost done. This part will return the dynamic values from database. Put this part in a different file. Remember, this file will be called from the AJAX part of the previous main file. So, be careful about naming the file.


<?php

$next_id = $_REQUEST["next_id"];

$content = "<option value=\"999\"> - - - </option>";

/*
  * Here, all return values (dropdown lists) are generated from predefined arrays,
  * To make them dynamic, you will have generate them by executing queries in your own Database
  * An example is given below for the first dropdown values
  */

if($next_id=="country"){
	$continent = $_REQUEST["continent"];
	$countries = array(
		"asia" => array("bd"=>"Bangladesh", "in"=>"India", "pk"=>"Pakistan"),
		"europe" => array("fr"=>"France", "sp"=>"Spain", "uk"=>"UK"),
	);
	
	 /****************************************************
	|	$q = " SELECT * FROM `table_name` ";
	|	$r = mysql_query($q);
	|	
	|	if(mysql_num_rows($r)>0){
	|		while($row=mysql_fetch_array($r)){
	|			$content.= "<option value=\".......\">..........</option>";
	|		}
	|	}
	 *****************************************************/
	
	foreach($countries["$continent"] as $key=>$val){
		$content.= "<option value=\"$key\">$val</option>";
	}
}

if($next_id=="city"){
	$country = $_REQUEST["country"];
	$cities = array(
		"bd" => array("dhaka", "chittagong", "sylhet"),
		"in" => array("delhi", "mumbai", "kolkata"),
		"pk" => array("islamabad", "lahore", "karachi"),
		"fr" => array("paris"),
		"sp" => array("madrid", "barcelona"),
		"uk" => array("london", "manchester"),
	);
	
	foreach($cities["$country"] as $key=>$val){
		$content.= "<option value=\"$key\">".ucwords($val)."</option>";
	}
}

echo $content;

?>

OK, that’s it. We are done.
So, don’t be late to try it now. Hope, it works just fine.

One thought on “Multilevel Dynamic drop down from Database Using AJAX in PHP”

Leave a Reply

Your email address will not be published. Required fields are marked *

4 × three =