Auto Complete Text box using AJAX in PHP

 
 
To view the live demo please enter your country name.
 
 
 
 
 
 
 
 
 
 
 

If you want to fill a text box content automatically from the database use the following code.

Step 1

Create a database test and add one table named countries with the following fields

id

value


Step 2

Insert some dummy values into the table TEST manually or download the database file from the following link

To download database file – Click Here

id

value

1

India

2

America

3

England

4

Canada


Step 3

Create one PHP page index.php and add the following code into that HTML page.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Auto Complete Input box</title>
<link rel="stylesheet" type="text/css" href="jquery.ajaxcomplete.css" />
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.ajaxcomplete.js"></script>
<script>
$(document).ready(function(){
 $("#country").autocomplete("ajaxcomplete.php", {
selectFirst: true
});
});
</script>
</head>
 
<body>
    <label>Enter Your Country Name : </label>
    <input name="country" type="text" id="country" size="20"/>
</body>
</html>

Step 4

Create another PHP page ajaxcomplete.php and add the following code into that PHP page.

<?php
$q=$_GET['q'];
$my_data=mysql_real_escape_string($q);
$mysqli=mysqli_connect('localhost','root','','test') or die("Database Error");
$sql="SELECT value FROM countries WHERE value LIKE '%$my_data%' ORDER BY value LIMIT 10";
$result = mysqli_query($mysqli,$sql) or die(mysqli_error());
 
if($result)
{
while($row=mysqli_fetch_array($result))
{
echo $row['value']."\n";
}
}
?>

Step 5

Open index.php file from WAMP server and enter your country name letters then it automatically display the full country name.

To download code - Click Here


You can leave a response, or trackback from your own site.

Leave a Reply