To make this tutorial, we will need:
- jQuery source – Certainly
- jQuery UI – one of the package for better GUI and autocomplete
- Basic knowledge about PHP and mySQL
That’s all we need, now let’s do the autocomplete in jQuery
Step 1: Create database example.
CREATE TABLE mytable (name VARCHAR( 255 )); INSERT INTO mytable (name) VALUES('Javascript'), ('JQuery'), ('PHP Framework'), ('Actionscript'), ('ASP.NET'), ('CodeIgniter'), ('Yii Framework'), ('Pascal'), ('C++'), ('C#'), ('Java'), ('ColdFusion');
Step 2: Create file php name server.php
<?php $mysql_server = 'localhost'; $mysql_login = 'root'; $mysql_password = ''; $mysql_database = 'fortest'; mysql_connect($mysql_server, $mysql_login, $mysql_password); mysql_select_db($mysql_database); $req = "SELECT name " ."FROM mytable " ."WHERE name LIKE '%".$_REQUEST['term']."%' "; $query = mysql_query($req); while($row = mysql_fetch_array($query)) { $results[] = array('label' => $row['name']); } echo json_encode($results);
In here, I name my database “fortest”, remember to change the database information (login, password, name) match with your server
Step 3: the index.php file look like
<!DOCTYPE head PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script> <script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"></script> <script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> <script type="text/javascript" src="login.js"></script> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> </head> <style> body{ margin:0 auto; max-width: 500px; padding: 30px; } </style> <body> <input id="search" type="text" name="term" /> <script> $(function() { $( "#search" ).autocomplete( { source:'server.php', }) }); </script> </body> </html>
DOne^^! Don’t forget to comment if you work it well