Not as fancy as the apple.com’s live search but I will explain how to make a live search for your site. I will use the Prototype and Scriptaculous Javascript libraries for this tutorial. I believe those are the best libs among all others.
Here’s what we’ll need. First create 2 blank files index.html and php.php. Place the prototype.js in the same folder and extract the scriptaculous libs in a folder named ’scriptaculous’.
We need to add a formfield and an empty DIV tag. The empty tag is where the results show up. Now we need to make a function called Autocomplete. So add this where the Custom JS functions go.
function autocomplete() {
new Ajax.Autocompleter(”autocomplete”, “autocomplete_choices”, “php.php”, {paramName: “autocomplete”, minChars: 1});
}
Here’s the final HTML:
autocomplete.txt
Ajax.Autocompleter is a built-in function of the Prototype library. The first param is the id of the formfield, the second is the id of where the suggestions will appear, the third of the php file where to make the request. The paramName is the name by which PHP gets the request and the last parameter is the number of character that needs to be typed before the process starts.
Now the PHP. Here it goes, i’ll explain later:
php.txt
First I created an array full of words. I used names of European countries.
Now note the $_POST … yes, that’s what we’ve put as the paramName in the Javascript.
So here’s the algorithm:
- Finding out the length of the string that’s entered in the formfield with the strlen function.
- Use a foreach loop so that each item in the array can be dealt with individually.
- Chopping off the words to the length that’s entered.
- If you entered “en” .. the length is 2 and the all the words will be chopped to 2 letters. France will become “fr” and England “en”.
- Matching the chopped word with the string that’s entered with the preg_match function. *
“en” matches with “en” not “fr” - Return the word that was originally chopped.
* Note: the string $entry is wrapped with / and /i … that’s for making sure that its not case sensitive.
The whole chopping thing is done to make sure that only words that START with “en” are listed. If that wasnt done, Sweden would also be listed. If you want it that way, make necessary changes.
Now its time to test. Open up index.html with your browser or just go http://localhost/whatever
You’ll see a humble text box. Enter something. Try E and you’ll see England and Estonia in a list. Neat!
Doesnt that look lame? Yup. Apply some CSS and make it cooler.
#autocomplete_choices {margin: -15px 0 0 -40px;}
#autocomplete_choices li {list-style: none; background: #fff; border-bottom: 1px solid #eee; padding: 2px;}
#autocomplete_choices li.selected {background: #ffb; }


Pingback
by Bookmarks about Scriptaculous
19 Aug 2008 at 07:45
[...] – bookmarked by 3 members originally found by reifdance on 2008-07-24 Ajax LiveSearch http://clnet.nl/blog/?p=19 – bookmarked by 1 members originally found by dstueber on 2008-07-23 [...]