Autocomplete Construction Tutorial

The picture above shows a Google search where the requested text is missing and Google provides us with choices that are nearly comparable to what we have entered. This will bring up an autocomplete window.

Requirements…
jQuery PHP

Demo   –  Download

To get started, create an HTML template

It’s worth noting that the demo format and training are not the same.

1<!DOCTYPE html>
2      <html>
3          <head>
4<meta content="fa" http-equiv="Content-Language">
5<script src="http://code.jquery.com/jquery-latest.js"></script>
6<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
7<title> AutoComplete - Live-Net.Ir </title>
8          </head>
9          <body>
10<input name="search" id=mysearchtype="text" onkeyup="sendData();">
11<div id="result" style="display:none"></div>
12          </body>
13 </html>

Build Ajax code to send information with jQuery.

1function sendData(){
2        var $val = $("#mysearch").val();
3 
4                $.post("info.php", {search: $val },
5                        function(data) {
6                                $("#result").fadeIn();
7                                $("#result").html( data );
8                        });
9}

So far, we’ve completed the template and Ajax code; the only thing left is to create a PHP file that will get and return the data.

1<pre><code>//
2 
3 $a[]="Iran";
4 $a[]="Tehran";
5 $a[]="PHP";
6 $a[]="Cinema";
7 $a[]="Ehsan";
8 $a[]="Farsi";
9 $a[]="Ghanon";
10 $a[]="Hesar";
11 $a[]="Professional";
12 $a[]="Javascript";
13 $a[]="Kid";
14 $a[]="Persian";
15 $a[]="Nina";
16 $a[]="Saeid";
17 $a[]="jQuery";
18 $a[]="Amanda";
19 $a[]="CSS3";
20 $a[]="لایونت";
21 $a[]="Doris";
22 $a[]="CSS";
23 $a[]="آرش";
24 $a[]="فارسی";
25 $a[]="Tove";
26 $a[]="سعید";
27 $a[]="دارو";
28 $a[]="رضا";
29 $a[]="Elizabeth";
30 $a[]="Ellen";
31 $a[]="Wenche";
32 $a[]="HTML";
33// If the request was sent, we will check the list above ….
34     if ( isset ( $_POST['search'] ) )$q=$_POST["search"];
35   $hint="";
36// Now we check the sent request (the first letter) and compare it with the above information …
37 if (strlen($q) > 0)
38   {
40   for($i=0; $i count($a); $i++)
41     {
42     if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
43       {
44// If the information entered is consistent with our information, we will use it:
45       if ($hint=="")
46         {
47         $hint=$a[$i];
48         }
49       else
50         {
51         $hint=$hint." <br/> ".$a[$i];
52         }
53       }
54     }
55   }
56 
57// If the information entered does not match our information, our output to the user: No offer
58   if ($hint == "")
59   {
60   $response="No offer";
61   }
62 else
63   {
64   $response=$hint;
65   }
66   echo $response;</code>

I hope this article is useful… If you have any questions,
please comment. Thank you.

%d bloggers like this: