PHP tutorial - Autocomplete


Autocomplete

Autocomplete can be a useful feature in a web page. It allows visitors type text in a text field and suggestion items that contains the text displays in a dropdown list for the them to select. When an item is selected from the list, this item will be displayed in the text field.

autocomplete dropdown list

In the image above the suggestion items displayed in the dropdown list are stored in a table called tblcountry that contains two columns cid, and cname. This table is in the Mysql database called dbcountry.

tblcountry

After you create the database, table, and add some example data as shown above, you will need to create a web page called autocomplete.php. It is the main page that shows you the Autocomplete form as shown in the image above. The content of autocomplete.php file is shown below. When the user types text in the text box, the text will be passed to the Ajax function called getCountry. In this function Ajax sends a request with the text in form of query string to the getcountry.php file on server. The getcountry.php file is processed on server at that time. It retrieves all country names that contain the text typed by the user in the text box and sends the result back to the autocomplete.php page.

<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<style>
#txtsearch{
width: 295px;
box-shadow: 0 3px 8px rgba(0, 0, 0, 0.25);
background-color:#fff;
border-radius: 3px 3px 3px 3px;

}
#lstcountry{
width: 300px;
display: none;
box-shadow: 0 3px 8px rgba(0, 0, 0, 0.25);
border-radius: 3px 3px 3px 3px;
}
</style>

<script>

function getCountry(q){
var lstcountry=document.getElementById("lstcountry");

if(q.length==0){
//hide dropdown list
lstcountry.style.display='none';
return;
}
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
//remove the old items
while(lstcountry.options.length > 0) lstcountry.length=0;

if(xmlhttp.responseText.length>1){
var result=xmlhttp.responseText.split("xxx");

var i;
for(i=0;i<result.length;i++){
lstcountry.style.display='block'; //show dropdown list
var selectBoxOption = document.createElement("option");//create new option
selectBoxOption.value =result[i].split("-*-")[0];//set option value
selectBoxOption.text =result[i].split("-*-")[1];//set option display text
lstcountry.add(selectBoxOption, null);//add created option to select box.

}
//open dropdown list
var len = lstcountry.options.length;
lstcountry.setAttribute('size', len);

}

}
}

xmlhttp.open("GET","getcountry.php?txtsearch="+q,true);
xmlhttp.send();
}


function Update(){

var txtbox=document.getElementById("txtsearch");
var lstcountry=document.getElementById("lstcountry");
//set selected item text of dropdown list to text box
txtbox.value=res.options[lstcountry.selectedIndex].text;
//hide dropdown list
lstcountry.style.display='none';
}

function hideThis(){
var lstofficer=document.getElementById("lstofficer");
lstofficer.style.display='none';
}

function detectEnter(e) {
if (e.keyCode == 13) {
hideThis();
return false;
}
}

</script>
</head>

<body>
<center>
<form id="form1">
<table border="0" cellspacing="0" cellpadding="0">
<tr>
<td><label for="txtsearchbox"></label>
<input name="txtsearch" type="text" id="txtsearch" size="50" onkeyup="getCountry(this.value)" tabindex=1/></td>

</tr>
<tr>
<td> <select name="lstofficer" id="lstcountry" onchange="Update()" onmouseleave="hideThis()" onkeypress="return detectEnter(event)" tabindex=2></select></td>
</tr>
</table>

</div>
</form>
</center>
</body>
</html>

Below is the content of the getcountry.php file.

<?php

//get the q parameter from URL
$q=$_REQUEST['txtsearch'];$DB_USER='test';
$DB_PASS='test';
$DB_HOST='localhost';
$DB_NAME='dbcountry';
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//escape special characters to prevent injection
$q=$mysqli->real_escape_string($q);
$query="SELECT cid, cname FROM tblcountry WHERE cname LIKE '%$q%'";
$result=$mysqli->query($query);
$resultstr="";
while ($row =mysqli_fetch_array($result))
{
extract($row);
if($resultstr==="") $resultstr=$cid."-*-".$cname;
else $resultstr.="xxx".$cid."-*-".$cname;
}

echo $resultstr;
$mysqli->close();
?>




Comments





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.