The Backend

Now it's time to create the server-side PHP file that will return our list of suggested resutls.  This is an extreamly simple PHP page that simply gets a list of titles from the database and returns each one.

The first thing we do is include our good old database abstraction file.  This file simply provides methods to access and query the database and is explained in the AJAX Chat Tutorial.
//Get our database abstraction file
If you needed to connect to a different datasource such as a MS SQL Server database or even an XML or flat file, you could change the database abstraction file's methods to handle this.  The one included in the download able source connects to a MySQL database.

Next we will make sure that a search parameter was passed in the query string and that it wasn't empty.  If either of these are true, we can't suggest anything, so we simply don't return anything.
///Make sure that a value was sent.
if (isset($_GET['search']) && $_GET['search'] != '') {
Next we're going to pull out the search parameter from the querystring and add slashes to any of the quotes to avoid any possible SQL errors that might occur from this.
	//Add slashes to any quotes to avoid SQL problems.
$search = addslashes($_GET['search']);
Our query is going to execute a SELECT statement that pulls all of the "DISTINCT" titles from our table where the first characters are the same as those already typed in the search box.
	//Get every page title for the site.
$suggest_query = db_query("SELECT distinct(title) as suggest FROM page WHERE title like('" .
$search . "%') ORDER BY title");
The % sign is a SQL wild card character that matches zero or more of any character(s).  We will also ORDER BY the title to make it a litter easier to visually parse.

The final step we need to do on the server-side is to loop through the results and return each one followed by a newline character "\n".
	while($suggest = db_fetch_array($suggest_query)) {
//Return each page title seperated by a newline.
echo $suggest['suggest'] . "\n";
And that's it for the server-side.

You can see how easy it is to create an AJAX Driven Auto-Suggest from this tutorial, and I'm sure your thinking about all sorts of neat ways to make this more powerful, more robust, or just plain different.