When you are using a web form you may need to generate suggestions for users to select an option from all available options.In my example , I have assumed that i have an input field called country.When a user types few text the webpage sends an ajax request shows the names of the countries which match with the user’s input.If user types “ind” it should show the names of the countries including keyword “ind”.
To complete the above objectives i am going to to use JQuery and Autocomplete plugin of JQuery.Here is the step by step guide-
1- Design a form-Design a simple form to get the country of user.
<form> Your Country: <input type="text" name="country" id="country" /> </form>
2- Add JQuery and autocomplete plugin-The next step is to add codes to includes JQuery and Autocomplete plugin and activate country field as autocomplete.In the following code i have used a PHP file “countrylist.php” which will extract the matching counties from MySQL database,you can replace this file name with your own.
<html> <body> <head> <script type="text/javascript" src="jquery.js"></script> <script type='text/javascript' src='jquery.autocomplete.js'></script> <link rel="stylesheet" type="text/css" href="jquery.autocomplete.css" /> <script type="text/javascript"> $().ready(function() { $("#country").autocomplete("countrylist.php", { width: 260, matchContains: true, selectFirst: false }); }); </script> </head> <body>
Your client side codes are almost complete now save this page as form.html or any name.
3- A PHP program to get matching names from database- To fetch the names from the database you can use the following PHP script-
<?php $q = strtolower($_GET["q"]); if (!$q) return; $uname=""; //Write username for database here $pass=""; //Write password for database user here $db=""; //write name of database here $con = mysql_connect("localhost",$uname,$pass); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db($db, $con); $q = "select DISTINCT name from country where name LIKE '%$q%'"; $r = mysql_query($q); while($res = mysql_fetch_array($r)) { $cname = $res['name']; echo "$cname"; } ?>
Don’t forget to assign the empty values of $uname ,$pass and $db .
You can download the files used in this tutorial from here-
The post Autocomplete an input field using AJAX, PHP, MySQL and JQuery appeared first on .