Click to find out more about our Work
October 26th, 2008

Tutorial : Auto Completer using Prototype, Script.aculo.us

11 Comments

Ajax.Autocompleter

Click Here for a Demo

It is compartively quite complicated than the earlier. It interacts with a external scripting file to retrieve its suggestions. This gives us the flexibility of having our own logic to retrieve the suggestions from a database/file etc. It also allows us to store a large pool of suggestions which would be nearly impossible to store at the client side.

It is also cleaver enough to make AJAX requests i.e, it pauses for a moment before it sends out a request, rather than flooding out requests.

Syntax

new Ajax.Autocompleter(id_of_text_field, id_of_div_to_populate, url, options);

The syntax is pretty straigtforward. The first 2 parameters are similar to Autocompleter.local except the 3rd which requires the URL of the page which will give the probable suggestions list of the input and the 4th parameter which share somewhat similar options compared to Autocompleter.local.

  • tokens – It lets you “reset” the suggestions every time a given key is pressed. If you want to enter multiple values, you need to tell Ajax.Autocompleter which is the delimiting symbol. Tokens are used for this purpose. If I specify { tokens: [';'] } then it means that the delimiting symbol here is “;”.
  • frequency – How frequently (in seconds) the input field should be checked for changes before triggering an Ajax request. Default – 0.4
  • minChars – The minimum number of characters that must be entered in the input field before an Ajax request is made. Default – 1

There is not much difference in the Syntax between the 2 Script.aculo.us autoCompleters, but just minor ones.
Now along with the syntax change there will be another addition here, i.e The Script file, to give the probable suggestions.

We will be using the same HTML page we used for the previous example, with the CSS styles. Although the javascript code now will be different.

Javascript Example Code :

<script type="text/javascript">
document.observe('dom:loaded', function() { //When the page is loaded, execute this
new Ajax.Autocompleter('state_input', 'state_suggestions','auto.php'); //follows the constructor. Since no options are specified, default values will be taken.
//1st parameter - state_input = input id
//2st parameter - state_suggestions = div id
//3st parameter -  auto.php = script file.
});
</script>

PHP File.
I`ll just tell you whats heppening here, in short. Now this php file retrieves all the states names from the database. You can retrieve whatever you want from the database. To create a database or add values to a database is beyond the scope of this tutorial.

  1. First we have defined the necessary variables used to connect to the database.
  2. We have established connection with the database using these variables and selected the database.
  3. Then we ran a query which retrieves all the states from the database. We store it in a array called ‘$suggestions’.
  4. We initialize the variable ‘$value’ from the input given by the HTML file. (the input tag)
  5. We cycle through every value of the array ‘$suggestions’ and then find for a match with the ‘$value’. If a match is found, we give it a CSS style (highlight-letter) which underlines the matched letter and bolds it out.
  6. We save all these matches inside a array called ‘$matched’.
  7. Once all the values from the ‘$suggestions’ are checked, the matched array is wrapped around a <ul> tag and echoed. Obviously this value is retrieved by the Ajax.Autocompleter and it populates the state_suggestions div.
<?php

//auto.php

$dbhost = 'localhost'; //host. 99% it is localhost
$dbuser = 'root'; //username
$dbpass = 'admin'; //password
$database = ''; // your database name

//Will Store all the state names retrieved from the database.
$suggestions = array();

/*Connection to database*/
$conn = mysql_connect($dbhost,$dbuser,$dbpass);
if (!$conn) die(mysql_error());
mysql_select_db($database, $conn) or die(mysql_error());

/*Query to the states table. It retrieves all the names of the states*/
$sql = "SELECT state FROM states";
$res = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($res)>0) {
	while($row = mysql_fetch_assoc($res)) {
	array_push($suggestions, $row['state']);
	}
}

// Frees up all the resources consumed by mysql connection.
mysql_free_result($res);
mysql_close($conn);

// if the user types in anything in the textbox, $value will store that value via $_REQUEST['input name'] method
// in our case the input name = state_input ( The textbox from the HTML page )
$value = isset($_REQUEST['state_input']) ? $_REQUEST['state_input'] : "";

//Will store all the input values that matches with the database suggestions.
$matched = array();

// Foreach statement, goes through each value of the array specified individually.
foreach ($suggestions as $suggestion) {
if (stripos($suggestion, $value) !== FALSE ) {
$match = preg_replace('/' .$value. '/i',"<strong>$0</strong>", $suggestion, 1);
$matched[] = "<li>$match</li>";
}
}

//Print all the suggestions. This is returned back to Ajax.Autocompleter.
echo "<ul>".join("", $matched)."</ul>";

?>

Well that was about it. This way you can create your own Auto Suggest Box with just 2 lines of code in Javascript using Prototype + Script.aculo.us.

Pages : 1 2 3

11 Responses to “Tutorial : Auto Completer using Prototype, Script.aculo.us”

  1. Toche
    August 20, 2010 at 2:38 pm

    In my page, I also have a calendar with a tooltip on mouse over of each day, now the tooltips are flickering. Any idea how to avoid this?

  2. Maria
    June 21, 2010 at 1:48 pm

    It works for one textfield, but I haven't been able to make it work for two or more textfields in the same page. Any ideas???

  3. prototype
    April 15, 2010 at 1:10 am

    works fine for me. thank you for the great tutorila!

  4. william kisman
    April 6, 2010 at 2:06 pm

    It works like a charm, Thanks
    this is the best auto suggestion tutorial out of many that I have came across

    • rezvie
      May 11, 2010 at 9:34 am

      anyone auto completer work in internet explorer 6?

  5. Mongol
    January 7, 2010 at 10:39 pm

    it doesnt work!

  6. ultragreen
    December 7, 2008 at 9:08 am

    One of my buddies is always talking about your blog at work – finally came and checked it out today, nice work! I’m subscribing to your rss feed – keep on posting!

  7. rubenhan
    December 6, 2008 at 1:48 pm

    Hi, thank you for this amazing tutorial. I downloaded the scripts and for some reason test2.html (autocomplete with PHP) does not work. I have Wamp installed in my computer and I changed the database information to match my Mysql database. I did use your sql file to write a table into my database. However, when I type into the text field, nothing happens. When I checked the Firebug, nothing happens. It looks like XMLHTTPRequest is not happening. Do you know what could be the problem? I did not change anything other than the database information.

  8. Tumba
    November 24, 2008 at 11:35 pm

    Hey, thank you so much for this tutorial. I’m really learning a lot from it. There is one problem though. I can’t get to page 3 of the tutorial. Every time I click on “3″ it reverts back to page 1. Could you see what’s going on? Thank you!

  9. tech news
    November 14, 2008 at 1:15 pm

    Prototype solved all java script issues.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code lang=""> <del datetime=""> <em> <i> <p> <q cite=""> <strike> <strong>