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.

http://hereswhatidid.com/coding/autocomplete/

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

jQuery Code:

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

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’);
mysql_select_db($dbname);
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’];
array_push($return_arr,$row_array);
}
}
mysql_close($conn);
echo json_encode($return_arr);[/sourcecode]

Comments are closed.