LiveSearch with Prototype.js
LiveSearch is a feature on many blogs these days, available as WordPress plugins or for implementation on non WordPress sites
. It’s a cool feature but how does it work, and can we customize it? Of course we can
.
To continue tha Ajax tutorials which was started with this simple one we now continue with a slight more complicated one.
For you who don’t know what Livesearch is we start with a small description
. LiveSearch is a search function on wep pages allowing the visitor to search and the result is presented in “real time”, either as an animated drop down box or perhaps the search form is filled with the results and the visitior get the feeling it all happens “live”
. An example can be seen by searching this site. The benefit with this is not only the cool feature but also a smaller bandwith usage as the whole page does not require reloading.
One drawback is that we need some javascript framework to be included on the pages which can be quite large at timesdepending on witch features are beeing used. For simpicity we are going to use the prototype and scriptaculous frame work. This can be achieved without these framworks too but it requiers more code, and besides we don’t need to invent the wheel again.
Besides the framwork we need three file for this to work:
- livesearch.php
The file is the main search file from where the Ajax call is made.
- general.js
Our javascript file which implement the features from the prototype framework
- results.php
The external file called by with Ajax and are responsible for the database search.
To make it clear how the program flow goes we can illustrate this with simple chart.
Let’t start with the livessearch.php file. This is mainly a search form from where the search term is passed to the functions in general.js.
livesearch.php
LiveSearch
That's all there is to it, the id's on the form, text and button is important because these are used by the javascript during the Ajax call. The div with the id="searchresults" is where the response from the Ajax call is to displayed.
No let's move on to general.js, this is where the meat is, at least for the client side.
general.js
function init(){
$('searchform').onsubmit = function() { doSearch();return false; };
}
function doSearch(){
new Ajax.Updater('searchresults', 'results.php?s=' + $('search_term').value,
{onComplete:function(){ new Effect.Highlight('searchresults');},
asynchronous:true});
}
Event.observe(window, 'load', init, false);
Lets go through the code line by line. On line 7 we put an onSubmit observer on the form in livesearch.php. This means that whenever the form is submitted the function doSearch is called by the observer. As you can see we are using the function $('searchform').onsubmit to do this. $(id) is a prototype function which returns the element with the id of the parameter. Quite handy. Normally we would do document.getElementById(id).onsubmit which is the same thing but less elegant.
Line 1 the init function is called automaic from line 8 when the page loads. So, when the search form is submitted the doSearch function is called and here the Ajax request is made to the results.php with ?s= as get variable. The Ajax.Updater has an additional option here and that is the Effects.Highlight and this is only eye candy . It makes the updated div searchresults flash once when the request is finished. There are several more effects like this in the prototype framework but that's besides the point.
Now, when the Ajax request is finished the searchresults div is updated like magic with the results from results.php. Results.php looks like this:
results.php
// Get the search term
$searchtearm = $_GET['s'];
// Connect to db
$conn = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$conn) {
die('Not connected : '. mysql_error());
}
// make foo the current db
$db_selected = mysql_select_db('foo', $conn);
if (!$db_selected) {
die ('Can't use foo : '. mysql_error());
}
// Get the search results
$res = mysql_query('SELECT * FROM table WHERE value = $searchterm');
// Echo the results
foreach.(..){
...
}
mysql_close($link);
I will not explain the PHP code for the results.php since this should be quite obvious. Besides the code is not complete it merley shows the outline. But it should get you started with Ajax.
That's all there is to it, now go home and try this for your self. Good luck.
Leave a Comment
You must be logged in to post a comment.
bill n
18 years ago
Thanks for this Erik – if I might venture, there is one thing missing from your site’s search function – a reset button that closes the result section
However, cools tuff as usual
Thanks, Bill
Fredrik Fahlstad
18 years ago
bill n: Thanks for the suggestion. And by the way the name is Fredrik.
bill n
18 years ago
now it’s even cooler – sorry Fredrik 😉
Now you have only one problem: when I type ‘search’ in the searchbox and the blind comes down with the results, if I scroll down with the mouse much of your formatting is destroyed (Firefox 2) – your graphics have not moved and neither have cookie input elements for the reply box so they are tangled up in everything else.
Ineterstingly using your new close function in the search area does not fix everything – you need to refresh for that.
Hope this helps
Cheers, Bill
Fredrik Fahlstad
18 years ago
bill n: Hm.. Strange, I’ll have to look into that. Thanks again.
J-Man
18 years ago
Can all this be accomplished without the use of frames? I mean without using a js bustout script?
David
18 years ago
Keep getting this error:
Error: $("s") has no properties
Source File: http://localhost/examples/ajax/livesearch/general.js
Line: 6
General.js
function init(){
$('searchform').onsubmit = function() { doSearch();
return false; };
}
function doSearch(){
new Ajax.Updater('searchresults', 'results.php?s=' + $('s').value,
{onComplete:function(){ new Effect.Highlight('searchresults');},
asynchronous:true});
}
Event.observe(window, 'load', init, false);
Any clue?
Fredrik Fahlstad
18 years ago
new Ajax.Updater('searchresults', 'results.php?s=' + $('s').value,
Should be:
new Ajax.Updater('searchresults', 'results.php?s=' + $('search_term').value,
Covi
17 years ago
Ummm… u can use prototype livesearch with search.php wordpress file.
results.php can’t necessary…
Think it 😉