AutoCompleter Tutorial
As always, links to a demo and ZIP at the bottom, Enjoy!
I thought i would write this tutorial because most of the auto completer applications i have seen just dump the code into a zip and tell you how to use it rather than how and why it works, knowing about this enables you to customise it a lot more (this has been demonstrated with the other apps i have written here)!

And so we begin:
JavaScript
<script src="jquery-1.2.1.pack.js" type="text/javascript"><!--mce:0--></script><script type="text/javascript"><!--mce:1--></script>
JS Explaniation
Ok, the above code it the guts to the script, this allows us to hook into the rpc.php file which carries out all the processing.
The Lookup function takes the word from the input box and POSTS it to the rpc.php page using the jQuery Ajax POST call.
IF the inputString is ’0′ (Zero), it hides the suggestion box, naturally you would not want this showing if there is nothing in the text box. to search for.
ELSE we take the ‘inputString’ and post it to the rpc.php page, the jQuery $.post() function is used as follows…
$.post(url, [data], [callback])
The ‘callback’ part allows to hook in a function, this is where the real magic if thats what you can call it happens.
IF the ‘data’ returned length is more than zero (ie: there is actually something to show), show the suggestionBox and replace the HTML inside with the returned data.
SIMPLE!
Now for the PHP Backend (RPC.php)
As always my PHP Backend page is called rpc.php (Remote Procedure Call) not that it actually does that, but hey-ho.
// PHP5 Implementation - uses MySQLi. $db = new mysqli('localhost', 'root' ,'', 'autoComplete'); if(!$db) { // Show error if we cannot connect. echo 'ERROR: Could not connect to the database.'; } else { // Is there a posted query string? if(isset($_POST['queryString'])) { $queryString = $_POST['queryString']; // Is the string length greater than 0? if(strlen($queryString) >0) { // Run the query: We use LIKE '$queryString%' // The percentage sign is a wild-card, in my example of countries it works like this... // $queryString = 'Uni'; // Returned data = 'United States, United Kindom'; $query = $db->query("SELECT value FROM countries WHERE value LIKE '$queryString%' LIMIT 10"); if($query) { // While there are results loop through them - fetching an Object (i like PHP5 btw!). while ($result = $query ->fetch_object()) { // Format the results, im using <li> for the list, you can change it. // The onClick function fills the textbox with the result. echo '</li> <li onclick="fill(''.$result->value.'');">'.$result->value.'</li> '; } } else { echo 'ERROR: There was a problem with the query.'; } } else { // Dont do anything. } // There is a queryString. } else { echo 'There should be no direct access to this script!'; } } ?>
PHP Explaination
Im not going to go into much detail here because there are loads of comments in the code above.
Basically, it takes the ‘QueryString’ and does a query with a wildcard at the en.
This means that in this case of the code each key-press generates a new query, this is MySQL intensive if its always being done, but short of making it exceedingly complex it is fine for small scale applications.
The PHP code is the part you have to change to work in your system, and all the it is updating the ‘$query’ to your database, you should be able to see where you put the table column name in etc…
CSS Styling – im using CSS3, YEA BABY! much easier although limits the functionality to Firefox and Safari.
<!-- .suggestionsBox { position: relative; left: 30px; margin: 10px 0px 0px 0px; width: 200px; background-color: #212427; -moz-border-radius: 7px; -webkit-border-radius: 7px; border: 2px solid #000; color: #fff; } .suggestionList { margin: 0px; padding: 0px; } .suggestionList li { margin: 0px 0px 3px 0px; padding: 3px; cursor: pointer; } .suggestionList li:hover { background-color: #659CD8; } -->
The CSS is pretty standard, nothing out of the ordinary.
Main HTML
<div>
<div>
Type your county (for the demo):
<input id="inputString" onkeyup="lookup(this.value);" size="30" type="text" />
</div> <div class="suggestionsBox" id="suggestions" style="display: none;">
<img style="position: relative; top: -12px; left: 30px;" src="upArrow.png" alt="upArrow" />
<div class="suggestionList" id="autoSuggestionsList">
</div>
</div>
</div>That is the main bit of HTML, really all you need to run this is an input text box with the ‘onkeyup’ function set to lookup(this.value); Also, i recommend NOT changing the ID of the input box, unless you change it in the Javascript section
Screenshots
I suppose you want to see some more screen shots…. OK.

And another one!

And now for the links… this is probably what you are all looking for!
Demo: Auto Complete Demo
Source ZIP: AutoComplete Source ZIP
If you need a domain to get you off your local test box buy domains at Network Solutions!
If you have any problems, just post them up here (as comments) and i am sure i can help you fix it
Thanks for the continued support,
Jamie.

Ok here is the code for turkish characters problems solving.
———-
$db = new mysqli(‘adress’,'user’,'pass’,'database’);
$db->query(“SET NAMES ‘latin5′”);
$db->query(“SET CHARACTER SET latin5″);
$db->query(“SET COLLATION_CONNECTION = ‘latin5_turkish_ci’”);
.
.
.
if(isset($_POST['queryString'])) {
$queryString = $db->real_escape_string($_POST['queryString']);
$queryString = iconv(‘UTF-8′,’latin5′,$queryString);
.
.
.
$strUTF = iconv(‘latin5′,’UTF-8′,$result->your_column);
echo(”.$strUTF.”);
————-
I have some problems with the code.
Don’t working with thai characters.
Hi, for some reason, this doesn’t work for me. I downloaded but when I try to type something in the input box, it shows me the entire PHP file starting from “real_escape_string($_POST['queryString']” i.e. the PHP file doesn’t appear to be processing. Any idea what could be causing this? Thanks.
hello, do you have a clean code (full code) of rpc to work with php4 , thanks
my problem is i have juste the big square black and nothing write in, the results search is ok but nothing appear in this box … thanks if you have a solution
[...] AutoCompleter – using jQuery(Ajax), PHP and MySQL, Tutorial and demo included. http://nodstrum.com/2007/09/19/autocompleter/ [...]
Here’s the COMPLETE WORKING CODE for PHP4, for those who are still running PHP4 instead of migrating to PHP5. I’ve spend 2 hours making sure everything was alright. Make sure to check for the ” and ‘ didn’t get replaced for erroneous stuff.
Author may feel like adding the php4 file to the zip too..which would be nice for clueless people
0) {
// Run the query: We use LIKE ‘$queryString%’
// The percentage sign is a wild-card, in my example of countries it works like this…
// $queryString = ‘Uni’;
// Returned data = ‘United States, United Kindom’;
// YOU NEED TO ALTER THE QUERY TO MATCH YOUR DATABASE.
// eg: SELECT yourColumnName FROM yourTable WHERE yourColumnName LIKE ‘$queryString%’ LIMIT 10
$result = mysql_query(“SELECT name FROM countries WHERE value LIKE ‘$queryString%’ LIMIT 10″);
if($result) {
//fetch rows from result set.
while ($row = mysql_fetch_assoc($result) ) {
echo ‘ ‘.$row['value'].”;
}
} else{
//echo ‘ERROR: There was a problem with the query.’;
}
} else {
// Dont do anything.
} // There is a queryString.
} else {
echo ‘There should be no direct access to this script!’;
}
}
?>
Sorry for double posting, but for those who want the file in PHP4, just head to http://www.almateria.net/rpc_php4.php
That’s all. Hopefully that will help someone!
Hi all,
Would it be possible for the suggestion div to overlay the rest of the form that’d be below the input box with autocompleter?
If the input is in the middle of a form whatever is below it is moved and depending on the rest of the page: messed up…
Thanks for this great tutorial and your help…
Hello everybody:
I have a problem. When put into operation on autocompletador, the results do not appear. Box appears in black, even makes the filter list, but it appears in black. Even when making a selection, input is blank. This is the code that I used.
real_escape_string($_POST['queryString']);
// Is the string length greater than 0?
if(strlen($queryString) >0) {
// Run the query: We use LIKE ‘$queryString%’
// The percentage sign is a wild-card, in my example of countries it works like this…
// $queryString = ‘Uni’;
// Returned data = ‘United States, United Kindom’;
// YOU NEED TO ALTER THE QUERY TO MATCH YOUR DATABASE.
// eg: SELECT yourColumnName FROM yourTable WHERE yourColumnName LIKE ‘$queryString%’ LIMIT 10
$query = $db->query(“SELECT Nombre_alimento FROM tb_alimentos WHERE Nombre_alimento LIKE ‘$queryString%’ LIMIT 10″);
if($query) {
// While there are results loop through them – fetching an Object (i like PHP5 btw!).
while ($result = $query ->fetch_object()) {
// Format the results, im using for the list, you can change it.
// The onClick function fills the textbox with the result.
// YOU MUST CHANGE: $result->value to $result->your_colum
echo ‘value.’\');”>’.$result->value.”;
}
} else {
echo ‘ERROR: There was a problem with the query.’;
}
} else {
// Dont do anything.
} // There is a queryString.
} else {
echo ‘There should be no direct access to this script!’;
}
}
?>
Hello everybody:
I have a problem. When put into operation on autocompletador, the results do not appear. Box appears in black, even makes the filter list, but it appears in black. Even when making a selection, input is blank. This is the code that I used.
real_escape_string($_POST['queryString']);
if(strlen($queryString) >0) {
$query = $db->query(“SELECT Nombre_alimento FROM tb_alimentos WHERE Nombre_alimento LIKE ‘$queryString%’ LIMIT 10″);
if($query) {
while ($result = $query ->fetch_object()) {
echo ‘value.’\');”>’.$result->value.”;
}
} else {
echo ‘ERROR: There was a problem with the query.’;
}
} else {
} else {
echo ‘There should be no direct access to this script!’;
}
}
?>
<>
in the while replace the “value” word for the name of yourColumnName. in your case raplace “value” for “Nombre_alimento”.
Yo tenia el mismo error pero ya lo acabo de solucionar.
Nice work for this tutorial.
I am just having a little trouble implementing more text boxes into this script. What i am after is when the auto complete box has done its stuff and the right data has filled it, it selects the rest of my data from the same MYSQL row and puts it into more text boxes.
This is a brilliant script, keep up the good work
Thank You.
[...] Autocomplete – jQuery ajax [...]
Hai!
this is best script for developers.
Thanks.
How do you use this together with MooTools? The script seems to break when used together with MooTools
How do we use this in conjuction with MooTools? It seems to break when I try to include MooTools.
[...] Autocomplete by AjaxDaddy. jQuery Autocomplete Plugin with HTML formatting. jQuery Autocompleter. AutoCompleter (Tutorial with PHP&MySQL). quick Search jQuery [...]
someone can zip and post the total files for php4 please, thanks again
hi again, i have found one day a zip file autocompleter but not this one post with (class.php , config.php, fonctions.php ,jquery.js , rpc.php) do you know where is the link to download ? thanks
Hi there,
First of all this is a great script.
Guys like me need guys like u
I spend about a whole night to get the up and down key functional and the enter key for selecting it and it stil doenst work for me.
Is there any way u can help me with this ?
With regards,
Jelle
Hi,
This is a great script. Great for newbie developers like me.
I was wondering :
1)is there a way to use the up and down arrows to scroll through the list
i’ve tried but can seem to get the logic going.
2)how can a add functionality to continue with the listing again even after selecting.
Just like in Yahoo! Mail or Gmail email address fields.
Thanks
Please I need the code for PHP4, the page posted by Nilopc not found. Thanks
[...] AutoCompleter Tutorial – jQuery(Ajax)/PHP/MySQL, show you how and why it works, knowing about this enables you to [...]
it is very useful. thank you.
[...] Autocomplete – jQuery ajax [...]
[...] AutoCompleter Tutorial [...]
Could you display a “no result!” when the suggestion doesn’t exist?
sorprendido, me gustaria aprobechar esto saludos!!
[...] Autocomplete by AjaxDaddy. jQuery Autocomplete Plugin with HTML formatting. jQuery Autocompleter. AutoCompleter (Tutorial with PHP&MySQL). quick Search jQuery [...]
[...] Autocomplete by AjaxDaddy jQuery Autocomplete Plugin with HTML formatting jQuery Autocompleter AutoCompleter (Tutorial with PHP&MySQL) quick Search jQuery [...]
[...] Autocomplete by AjaxDaddy. jQuery Autocomplete Plugin with HTML formatting. jQuery Autocompleter. AutoCompleter (Tutorial with PHP&MySQL). quick Search jQuery [...]
Hello,
Any idea, how to insert selected value into mysql db??
I keep getting
ERROR: There was a problem with the query.
even though I ma using this code.
$query = $db->query(“SELECT value FROM countries WHERE value LIKE ‘$queryString%’ LIMIT 10″);
Any ideas why??
Thanks
John: That query seems perfectly fine in its syntax, however, I would speculate that you have not imported the SQL file resulting in the query not being able to find a table or a column in a table, and thus returning you an over-friendly error.
[...] AutoCompleter Tutorial – jQuery(Ajax)/PHP/MySQL Lanuch Demo/site [...]
[...] AutoCompleter Tutorial – jQuery(Ajax)/PHP/MySQL, show you how and why it works, knowing about this enables you to [...]
[...] Autocomplete by AjaxDaddy. jQuery Autocomplete Plugin with HTML formatting. jQuery Autocompleter. AutoCompleter (Tutorial with PHP&MySQL). quick Search jQuery [...]
[...] AutoCompleter (Tutorial with PHP&MySQL). [...]
[...] Autocomplete – jQuery ajax [...]
[...] Autocomplete by AjaxDaddy.jQuery Autocomplete Plugin with HTML formatting.jQuery Autocompleter.AutoCompleter (Tutorial with PHP&MySQL).quick Search jQuery Plugin.?????(Inline Edit & Editors)jTagEditor.WYMeditor.jQuery [...]
Hi, I have got this working good in all tested browsers but in Opera and Firefox there’s a small nag in the suggestionbox first row. The characters that appear on the first row are “”.
This row is not selectable so it’s not db output. I roled that out by not doint any db at all. It’s not the css, ruled that out by having none at all. Still these characters show. In IE it looks great. Seen this? any ideas?
cheers, //J
Hi Jan,
these characters seem to be added when Windows gets hold of the file when editting.
To fix this have a look at line 1 in all the files associated with my auto-completer. In one of them will be these characters.
If they are not showing up in notepad I’d whatever you use to edit files have a look at it through an online editor if you have one, but I’m pretty sure they can be seen just opening the files in notepad or wordpad.
Thanks for using my script!!
Jamie.
good idea, but no. The editor is utf-8 and I have checked all files on the host too with vi. Nothing to bee seen there. I also deleted all lines except code and html from the index file. I have also tried three different versions of jquery.
Hi Jan,
it is defineatly in one of the files, i have seen this before.
Can you point me to the URL so i can have a look for myself?
Jamie.
cheers man, indeed…
[root@test 3]# cat index.htm
<!DOCTYPE html PUBLIC “-//W
Deleting this row in any editor still kept the garbage.
big thx, Jan
Hi again Jan,
Yes that looks like i thought it might, ha.
Which editor are you changing this line in?? vi/emacs??
Sorry this is taking a while to debug – it is the editors adding things in.
Have you got access to cPanel or a control panel with a file manager in it? ie: you can see the raw file inside a ‘textarea’ box. I am guessing if you change it there it may bypass the editor – give that one a go and let me know.
Good Luck,
Jamie.
Hello John.
The problem with your query is that the quotes are not the ones that should be in SQL… try this:
Jamie.
[...] Autocomplete by AjaxDaddy. jQuery Autocomplete Plugin with HTML formatting. jQuery Autocompleter. AutoCompleter (Tutorial with PHP&MySQL). quick Search jQuery [...]
thanx