PHP tutorial - ajax dropdownlist


AJAX dropdownlist

In this tutorial, you will learn to populate a dropdownlist without reloading the web page by using AJAX and PHP. For example, there are two dropdownlists in a web page. One dropdownlist contains a list of ministries. Another dropdownlist lists departments in the ministry selected from the first dropdownlist.

select an item from this list dropdownlist

This is the result of the first dropdownlist selection

The lists of ministries and departments are read from two tables of a Mysql Server database. In this tutorial, the two table are tblminstry and tbldepartment. These tables are in the test database. You need to create a new user account to manage the database. This account has user name "test", and password "test". The user account information is useful as you need it to connect to the database.

tblministrytbldepartment

After you create the test datbase, tblministry, tbldepartment, and add some example data to the tables as shown in the images above, you can start to create a new php file to handle connection and read data from Mysql Server. This php file is called datahandler.php. Its content is shown below.

datahandler.php

<?php
class DataHandler{
private $con;
private $db;

public function DataHandler($DB_HOST,$DB_USER,$DB_PASS,$DB_NAME){

$this->con=mysql_connect($DB_HOST,$DB_USER,$DB_PASS);
if (!$this->con) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
$this->db=mysql_select_db($DB_NAME,$this->con);
if (!$this->db) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}

}

public function displayMinistries(){

// Now let us start executing the query
$query="SELECT * FROM tblministry";
$result=mysql_query($query) or die("Error in data retrieval");
$rnum=mysql_num_rows($result);
if($rnum>0){
echo "<select name=\"lstministry\" id=\"lstministry\" onChange=\"getdept(this.value)\" onFocus=\"getdept(this.value)\" style=\"width: 200px\">";
echo "<option value=\"0\">...Select a ministry...</option>";
while ($row = mysql_fetch_array($result))
{
extract($row);
echo "<option value='$row[0]'>".$row[1]."</option>";

}
echo "</select>";
}

}

public function getDepartments($mid){

//select all departments in the specified ministry
$query="SELECT * FROM tbldepartment WHERE mid='$mid'";
$result=mysql_query($query) or die("Errror in data retrival");
$textresult="";
while ($row = mysql_fetch_array($result))
{
if($textresult==="") $textresult=$row[0]."-*-".$row[1];
else $textresult.="xxx".$row[0]."-*-".$row[1];
}
echo $textresult;
}


public function closeConnection(){
mysql_close($this->con);
}

}

?>

When you create an object of the DataHandler class and pass host name, user name, password, and database, it will connect the database. The two dropdownlists are in the index.php page. The displayMinistries member function is called from the index.php page to populate the first dropdownlist. In the getdept function defined in index.php, AJAX code is written to send a request with the id of the ministry selected from the first dropdownlist to the listdept.php file. The getDepartments function that works in the listdept.php will send a result string of departments for a selected ministry back to the index.php page. The result string are split and populated in the second dropdownlist.

index.php

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Comment</title>
<script>

function getdept(str)
{


if (str.length==0)
{
return;
}

var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{

//reference to the second dropdownlist
var lstdepartment=document.getElementById("lstdept");
//clear the second dropdownlist
while(lstdepartment.options.length > 1) lstdepartment.options.length=0;
//populate items in the second dropdownlist
if(xmlhttp.responseText.length>1){

var depts=xmlhttp.responseText.split("xxx");
var i;
for(i=0;i<depts.length;i++){

var selectBoxOption = document.createElement("option");//create new option
selectBoxOption.value = depts[i].split("-*-")[0];//set option value
selectBoxOption.text = depts[i].split("-*-")[1];//set option display text
//alert(depts[i].split("-*-")[1]);
try{
lstdepartment.add(selectBoxOption,null);//for browers: firefox, chrome....
}catch(err){
lstdepartment.add(selectBoxOption); //for IE browser

    

}


    }

  }
}
}

//send a request to the listdept.php page
xmlhttp.open("GET","listdept.php?q="+str,true);
xmlhttp.send();


}
</script>

</head>

<body>
<?php
include("datahandler.php");
$dbhandler=new DataHandler("localhost","test","test","test");

?>
<form id="form1" name="form1" method="get">
<table>
<tr>
<td>
<?php
$dbhandler->displayMinistries();
?>
</td>
<td>
<select name="lstdept" id="lstdept" style="width: 200px">
</select>
</td>

</tr>

</table>

</form>
</body>
</html>

listdept.php

<?php

include("datahandler.php");
$dbhandler=new DataHandler("localhost","test","test","test");
$dbhandler->getDepartments($_REQUEST['q']); //
$dbhandler->closeConnection();
?>

You can download the datahandler.php, index.php, and listdept.php files from here.



Comments

CAPTCHA image




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.