Ajax Autocomplete jQuery Plugin

This is a nice little plugin for easily adding auto-complete functionality to form fields. All it looks for is a datasource formatted as JSON. I’ve put an example here using PHP to access a dinosaur name database returning the previously stored values.


The project site is here: http://jqueryui.com/demos/autocomplete/

jQuery Code:

[sourcecode lang=”javascript”](function($) {
$(function() {
$( ‘#s’ ).autocomplete({
source: ‘tags.php’,
minLength: 2

PHP for JSON Remote Data:

[sourcecode lang=”php”]$return_arr = array();

$dbhost = ‘hostname’;
$dbuser = ‘username’;
$dbpass = ‘password’;
$dbname = ‘databasename’;

$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die (‘Error connecting to database’);
if ($conn) {
$fetch = mysql_query("SELECT * FROM `sample-dinosaurs` WHERE DinoName LIKE ‘%".$_GET[‘term’]."%’");
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array[‘label’] = $row[‘DinoName’];
echo json_encode($return_arr);[/sourcecode]