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.

[...] by AjaxDaddy . jQuery Autocomplete Plugin with HTML formatting . jQuery Autocompleter . AutoCompleter (Tutorial with PHP&MySQL) . quick Search jQuery Plugin [...]
Works great as a single text input but can’t get 2 to work on the same page?
thank you very much. this is what im looking for. great share
how can i hide the ID(field) and display the name?
Thanks, It helps a lot.
Please share or help me to acheive the same AJAX and JSP.
Thanks in advance
Pavan
thanks alot , but I have problem with persian langauge . it doesn’t work for persian .what should I do?
thanks,great one,but i need to display the details of country like capital,curency,isd code etc
how i can display all the fields of selected country
[...] Autocomplete by AjaxDaddy. jQuery Autocomplete Plugin with HTML formatting. jQuery Autocompleter. AutoCompleter (Tutorial with PHP&MySQL). quick Search jQuery [...]
TransportLouisVuittonRidingABicycleBagToHaveAPassionForTravelling,?????? ???,HowYouCanIdentifyAFakeLouisVuittonHandbags,???? ??,LvBagsBothEachAndEveryOperateMorePast
[...] Autocomplete by AjaxDaddy. jQuery Autocomplete Plugin with HTML formatting. jQuery Autocompleter. AutoCompleter (Tutorial with PHP&MySQL). quick Search jQuery [...]
Nice article but I have one problem:
When I typed something but I don’t want to select the suggested item. Textbox is empty and don’t show value in textbox, how to do this?
Please let me know if you’re looking for a writer for your blog. You have some really good articles and I believe I would be a good asset. If you ever want to take some of the load off, I’d
really like to write some content for your blog in exchange
for a link back to mine. Please shoot me an email if interested.
Many thanks!
Extraordinary things. Little ones cherished it. Created two or three tweeks
as did not have mushrooms and chosen parmesan as a substitute.
sooooo yummy. Very simple. Cheers for this.
i am using doo php when i use code i am getting error as $ is not defined in my console can any one help me please……
Hi.
Just wanted to say i´m having a problem with spanish characters as ñ as in caña.
Any idea how to solve it
I have been surfing online more than three hours today, and this is the best article I’ve come across. I’m a content fiend so I’ve actually read a lot already.In my opinion, if all web owners and bloggers made as good content as youhave, the net would bemuch more useful than ever before.
Your method of describing everything in this paragraph is
in fact fastidious, every one be able to effortlessly know it, Thanks a lot.
There are some natural blood steps to detox your body products to see what product best matches with your body.
They are called primitive because these cells never
did develop into mature cells to form various parts of the body and provide energy.
Here is my homepage the best way to cleanse your body
Hi, great tutorial.
I just found one little problem in the way the PHP file interpret results :
When you type, say, “F”, it will show every country starting with F. Then if you type R, it will reduce the list to country starting with “Fr”
But if you type F then T for instance, there are no countries starting with Ft, but instead of hiding the choice box, it will continue to display the last coherent value (here, countries starting with “F”)
Hi, it works great, but i can’t make it work with two autocomplete on the same page, which i need for a project; can you help me? thanks
Perfect for a chillout slow jam hangout after the clubs close.
Just a few evenings ago we were at a meeting with other volunteers to find out more about RSVP:
the Retired Senior Volunteer Program. We are literally not
the same person we were a minute ago, let alone a day, a month or a year ago.
The Squeezbox Boom radio from Logitech is not just an Internet
radio. Some models, if they are equipped with remote start,
will allow the customer to start the engine through the app wirelessly,
doing so from any place where there is a cell phone
signal available. Kevin Smith is a stand up comedian known for directing
feature film comedies like Clerks, Dogma and
Jersey Girl.
Dominion: Intrigue is a standalone expansion for the
award-winning Dominion card game that shook
the gaming world in 2008. Caution: when a hole is made in a
can, there may be metallic edges that can cut one’s mouth. This classic game integrates all-out entertainment with vocabulary enhancement in one amazing game.
[...] McConnell Published: September 19, 2007 Link: http://www.nodstrum.com/2007/09/19/autocompleter/ Excerpt: “I thought i would write this tutorial because most of the auto completer [...]
[...] Nodstrum jQuery Auto Completer [...]
zsC
[...] Leia maisDemonstração [...]
It’s difficult to find experienced people on this subject, but you sound like you know what you’re talking about!
Thanks
Bon travail, A bient?t. Je laisse mon premier commentaire sur ce site