In the last few days I’ve started using the jQuery JavaScript library. To experiment with this great piece of software I’ve decided to implement an AJAX auto-complete feature. jQuery makes remote scripting a piece of cake and that led me to spend more time coding additional functionalities for the auto-complete field. In this post I’ll explain how to use my auto-complete field and in a following post I’ll explain all the code. So let’s start!

Before continuing let’s see how the auto-complete field looks like. Start typing some color name in the input field bellow to see how it works:

Pretty hugh? Besides the auto-complete code we need the jQuery library along with its Dimensions plug-in (all files are linked at the end of this post). Let’s include the files into our page:

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dimensions.js"></script>
<script type="text/javascript" src="autocomplete.js"></script>

Now we need to call the function that will bring life to our auto-complete field - setAutoComplete.

<script type="text/javascript">
$(function(){
    setAutoComplete("searchField", "results", "autocomplete.php?part=");
});
</script>

The call to setAutoComplete is inside a jQuery special code that is only executed when the DOM is ready, or in other words, when all the code is already loaded. The setAutoComplete function takes 3 parameters:

  • the id of the input field
  • the id of the div that will hold the returned data
  • the URL of the remote script that will process the request

Be aware that the URL should reflect your remote script and that it will be combined with the text typed in the input field.

Now we include our stylesheet to define the look of the elements. We need to define the styles of the div that will contain the results, they include two classes for the selected and unselected items. Take a look at the CSS file linked at the end of this post. There is also a style for the input field.

<link rel="stylesheet" href="autocomplete.css" type="text/css">

To finish the client side part now we need to define the code of the input field as follows:

<label for="searchField">Colors: </label>
<input type="text" id="searchField" name="searchField">

We are almost there! Now that the client side is finished it’s time for the server script. Here is an example of a script that try to match colors. I’m using PHP but you can use whatever language you prefer for the job, of course. You just need to return the results as an array encoded as JSON.

// define the colors array
$colors = array('black', 'blue', 'brown', 'green', 'grey',
                'gold', 'navy', 'orange', 'pink', 'silver',
                'violet', 'yellow', 'red');
 
// check the parameter
if(isset($_GET['part']) and $_GET['part'] != '')
{
	// initialize the results array
	$results = array();
 
	// search colors
	foreach($colors as $color)
	{
		// if it starts with 'part' add to results
		if( strpos($color, $_GET['part']) === 0 ){
			$results[] = $color;
		}
	}
 
	// return the array as json
	echo json_encode($results);
 
	// or return using Zend_Json class
	// require_once('Zend/Json/Encoder.php');
	// echo Zend_Json_Encoder::encode($results);
}

Done! As said before, we return the data as an array encoded as JSON. If you are running PHP >= 5.2.0 or the json extension you simply use json_encode for the job. Another option is to use Zend_Json_Encoder from the Zend Framework!

You should have a working auto-complete field by now! Note that we don’t need to explicit create the result div because it’ll be created automatically. You should also note that the current script can be improved a lot and is limited to just one auto-complete field per page!

Keep tuned, in the next post I’ll explain how the JavaScript works!
Thank you!

Update: Click here to read the post where I explain the JavaScript code!

Files needed:

Auto-Complete (All files)
jQuery JavaScript Library
jQuery Dimensions Plug-in
Zend Framework