Using Ajax Agent and PHP for Auto-Complete

Written By: Jay

- 15 Jun 2006 -
















Description: In this HOWTO I will explain how to use AjaxAgent and PHP to create an Ajax Auto-Complete box with a drill-down list of data. The UI is very simple. It consists of a TextBox to enter an Artists' Name, a selectbox to display the Albums and an unordered list to display the songs on an album.

  1. Auto Complete
  2. Posting Back
  3. On Your Own

Part 1: Auto Complete

Start by creating a new PHP page and placing the agent.php (Ajax Agent) file in the same directory. Open your new PHP page in an editor and start hacking away.

First create the HTML Form controls we will be using:

  1. txtArtists = TextBox to type the ArtistName in.
  2. matches = A SelectBox with an onclick event which will be used to send the ArtistName to the AlbumSearch method we will be creating.
  3. txtArtistID = Hidden to hold the selected ArtistName (js cannot see the select box because it is hidden?)
  4. htmlOutput = An empty DIV when we will be creating a list of Albums
  5. htmlOutputTracks = An empty DIV when we will be creating a list of Tracks

HTML:

name="artistName" id="artistName" size="20" type="text" onkeyup="GetArtist();return false;" autocomplete="off">
id="matches" style="VISIBILITY: hidden" onclick="MatchSelected(this);" >  
id="htmlOutput">

id="htmlOutputTracks">

Now at the top of the page add a new PHP script tag with an include for agent.php and a new $agent object. Any other PHP code that we must be placed before (above) this code.

PHP:

/* my functions go here
and
here
*/
 
include_once("agent.php");
$agent->();

Next we'll add the first function that search for Artists by name.

GetArtist function works by taking a string parameter and uses it to search for Artists who's name begin with it using a Regular Expression. The list of Artists are stored in an Array array and we will use a foreach loop to search the Artis Name. If we find a match we add it to a second $results array and them move on to the next item in the array. Once we have reached the end of the $Artist Array we re-sort the $results Array. Lastly we only want to return a list of Artist Name so we'll use the array_values($results) function.

PHP:

function GetArtist( $text ){
include("dbconn.inc.php");
$strSQL = "SELECT * FROM artists WHERE artist_name LIKE '$text%'";
 
$db= mysql_connect($dbHost, $dbUser,$dbPwd);
mysql_select_db($dbName,$db);
$result = mysql_query($strSQL,$db);
$num = mysql_num_rows($result);
 
$listArray = array();
$i=0;
while ($i<$num)
{
$artist_name = mysql_result($result,$i,"artist_name");
$listArray[$i] = $artist_name;
$i++;
 
}
 
asort( $listArray );
mysql_close($db);
 
return $listArray;
 
}

So far we have a form and a PHP function now we need to wire up some ajax to make this work.

*There are some visibility issues with JS and the HTML Controls so the