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.

You’ve left yourself wide open for SQL injection here… Take a look at the mysqli_real_escape_string() function to protect yourself.
Hi Mike,
Good spot, i wasn’t writing it with security in mind
I have the demo version running with a user who can only ‘SELECT’ from the database.
This has now also been updated in the Source ZIP
For those who are interested, this is what was changed in the code:
Replace
$queryString = $_POST['queryString'];With
$queryString = $db->real_escape_string($_POST['queryString']);
Cheers for your help Mike!
Jamie.
Hi Jamie,
I’ve got this script working, but the highlighting of the list items does not work unless I have this added to my html form.
If i add that line of code it works, but it stuffs up all the sizes of my html controls.
I don’t really understand how to use DTD and really don’t want it.
Is there a way of getting the list items highlighed without using the DTD?
Thanks
Tristan
When I submitted it removed the line of code. So above doesn’t make much sense!
The line I’m talking about is the very top line of the html page which references the DTD, if I don’t have that the highlighting doesn’t show. If I add it, it changes all the sizes of my listboxes and effects the look of some of my controls.
I figured out my problem. I hadn’t correctly specified the width=220px:, instead in my tags I had width=220 and when I added the DTD it caused problems with my page.
But I have another question. How do you get the suggestionbox to lose focus if the user doesn’t select an item but clicks elsewhere.
Hi Tristan,
Sorry you had to figure that all out one your own last night, i could not look at another computer screen when i got home last night…
With regards to the DTD i never really pay much attention to them, the reason its in the demo is because i used Microsoft Expression Web to create it as a test.
Now… to make it loose focus:
The textbox already looses focus, but we have to hook a new property to it.
Add this into the tag:
onblur="$('#suggestions').hide();"Let me know if that solves your problem.
Jamie.
Hmmm,
Adding the above code breaks the fill() function because it has in-effect lost focus and is hiding.
Let me have a play around.
Jamie.
Ok, i got it.
We need to replace the fill() function to add a timeout… do the following.
Replace the fill() function with
function fill(thisValue) {
$('#inputString').val(thisValue);
setTimeout("$('#suggestions').hide();", 200);
}
Add this onBlur to the ‘input’ tag
onblur="fill();"That should be it
This has also been updated in the ZIP!
Jamie.
This looks like a really good tutoral, very well explained – its a shame others dont explain the code they provide in a tutorial instead of just handing it out!!!
the script it failed. send to me script original of autoComplete.
Hi Edwin,
Can you be a bit more specific about how its not working, or provide a link to the script on your server.
Jamie.
Minor javascript error on the demo page:
- urchinTracker is not defined -
urchinTracker();
FF on Mac and maybe others don’t allow keyboard to select values. Some of the others like YUI and Scriptaculous allow for this. Are you working on something similar?
Hi Joel,
This will be implemented in v1.2
Jamie.
Hi Rrrrrrrrr,
Thanks for picking that one up… im assuming you have firebug aswell
Fixed!
Jamie.
Hi,
Its great.Thanks
[...] Mcconnell has taken the age old classic Ajax autocompleter, and has created a simple tutorial using jQuery and PHP. Jamie takes time to explain the “why” as much as the [...]
[...] Nodstrum » Blog Archive » AutoCompleter Tutorial – jQuery(Ajax)/PHP/MySQL (tags: jquery ajax autocomplete php tutorial javascript) [...]
Very nice tutorial. To be really picky, you should separate content and behaviour by adding event handlers with $(“#id”).bind(“click”, …
Dave
Hi Dave,
Thanks, i’ll look into doing that in my next tutorial!
Thanks for the pointer
Jamie.
Hi,
nice tutorial.
Here some ideas:
- the left/right/up/down cursor-keys shouldn’t send a request. SHIFT+Key and ALT-GR+Key shouldn’t send 2 requests.
- real supporting for the space char: “a bla foo” gives at this time the same result list like “a”
Best regards.
[...] Mcconnell has taken the age old classic Ajax autocompleter, and has created a simple tutorial using jQuery and PHP. Jamie takes time to explain the “why” as much as the [...]
[...] Nodstrum » Blog Archive » AutoCompleter Tutorial – jQuery(Ajax)/PHP/MySQL (tags: ajax form jquery php tutorial autocomplete guide webdesign webdev web development) [...]
[...] Nodstrum » Blog Archive » AutoCompleter Tutorial – jQuery(Ajax)/PHP/MySQL (tags: ajax jquery php autocomplete tutorial javascript form development *) [...]
Hey nice post can u please tell me how to use using Rails.
Hi Arun,
I am not using Rails in this tutorial, it is pure PHP
Jamie.
Nice script. I’m from Brazil and here we have the words with “´`ç” and the word example “Senhor dos Anéis” at this script appear “Senhor dos An?” how i correct this?
For the Russian language with the win-1251 codepage (not UTF8) must convert data between codepage. Both$queryString and $result->value.
$queryString = iconv(‘UTF-8′, ‘CP1251′,$queryString);
…
$strUTF = iconv(‘CP1251′, ‘UTF-8′,$result->value);
echo ”.$strUTF.”;
Very nice script, thanks. But still I have some problems with it.
How to make the suggestionsBox to overlayother web content that is present before suggestionbox is displayed? It normaly does cover rest of the page under it in IE7 but not in firefox. I tried z-index without any success.
I also tried to change postition property to absolute which solves my problem, but then position of suggestbox is changing depending on the browser window size.
Does anyone know what how to solve this issue?
Thanks Michal
[...] Nodstrum » Blog Archive » AutoCompleter Tutorial – jQuery(Ajax)/PHP/MySQL (tags: ajax jquery php tutorial) [...]
Nice tutorial! Thanks for taking the time
Just two quick things:
1. “As always my PHP Backend page is called rpc.php (Remote Procedure Call) not that it actually does that, but hey-ho.”
Can I suggest not naming this file incorrectly?
It’s not an RPC!
2. Also. Please don’t use CSS3 yet.
not working
very cool example.
[...] Nodstrun.com han publicado un sencillo tutorial en el que nos explican cómo implementar de forma elegante la funcionalidad de [...]
Can you please make a php4.3 version? I’ve tried it for a couple of hours now, without the big succes
[...] AutoCompleter Tutorial – jQuery(Ajax)/PHP/MySQL (tags: webdev jquery ajax javascript) [...]
not working well when i type space in first position……
I have only access to PHP4 so I get some errors.
Can the code be written for PHP4? If so what needs to be changed?
Love this.
Best
B
Hie. I have been trying this code but without success. I am new to PHP Web development and I guess there is something I am not doing right. I merely copied the files in my dreamweaver environment. Changed the database connection and query to suit my environment. However, every time I load the page and type something, I get an erreor to the effect referencing the line to do with Color style. Please advise. Are there classes to load before using your code snippets?
[...] Script : http://nodstrum.com/2007/09/19/autocompleter/ [...]
[...] publicado en Nodstrum un tutorial sobre como hacer un autocompleter con tecnología JQuery os recomiendo que lo leais, [...]
[...] ??? ????? Nodstrum ? Blog Archive ? AutoCompleter Tutorial – jQuery(Ajax)/PHP/MySQL __________________ |^^^^^^^^^ .|| | samry. ___ ||’""|""___, | ___________ l [...]
Here is a code compatible with PHP4 . Replace rpc.php with this content .
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 `value` FROM `countries` WHERE `value` LIKE ‘$queryString%’ LIMIT 10″);
//if($result) {
//fetch rows from result set.
while ($row = mysql_fetch_assoc($result)) {
// 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 ”.$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!’;
}
?>
Nice, though I’d still go for writing Ajax in a RAD Framework like ours…
A version of rpc can be better for dynamic search.
include(“classe_database.php”);
$database = new Database();
if(isset($_POST['queryString'])) {
$queryString = $_POST['queryString'];
$tabella = $_POST['tabella'];
$campo = $_POST['campo'];
if(strlen($queryString) >0) {
$sql = “SELECT $campo FROM $tabella WHERE $campo LIKE ‘$queryString%’ LIMIT 10″;
$database->Query($sql);
$result = $database->result;
$num = mysql_num_rows($result);
if($result) {
for($i = 0; $i ‘.mysql_result($result,$i,$campo).”;
}
} else {
echo ‘ERRORE: Problema nella query.’;
}
} else {
}
} else {
echo ”;
}
and this is the javascript code must be set on header
function lookup(inputString) {
if(inputString.length == 0) {
// Hide the suggestion box.
$(‘#suggestions’).hide();
} else {
$.post(\”rpc.php\”, {queryString: \”\”+inputString+\”\”,tabella:\”prova\”, campo:\”\”+document.modulo_prova.cerca.value+\”\”}, function(data){
if(data.length >0) {
$(‘#suggestions’).show();
$(‘#autoSuggestionsList’).html(data);
}
});
}
} // lookup
function fill(thisValue) {
$(‘#inputString’).val(thisValue);
setTimeout(\”$(‘#suggestions’).hide();\”, 200);
}
and the form can be search in different column
echo “”;
$select2.= “titolo”;
$select2.= “descrizione”;
echo “”;
echo $select2;
echo “”;
echo ” Cerca: “;
echo ”
“;
Can be a little mod
Oh sorry, the post doesnt good cuz block html tags. Email me so i can give you all code.
[...] Collis wrote an interesting post today!.Here’s a quick excerptI 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 … [...]
Nice tutorial, how do i make that the swedish letters å,ä and ö can be displayed in the suggest box?
Awesome tutorial. finally somone who explains the code. I was wondering is it possible to make some additions so text is added to the text box as user is typing. so he can just press enter? also if its possible to make up and down arrow keys work ..rather than mouse click (on the auto complete list show)
Thanks a lot again!
I have some problems with the code. Don’t working with some turkish characters like ‘?’. Saying ‘ERROR: There was a problem with the query.’ Another problem is how can i send suggested data to my search page? I did use action=”xxx.php” method=”POST” in form field but not working. Please advise me. Thanks.