#! /usr/bin/perl -w # dynamic select boxes, using a db use strict; use CGI::Ajax; use CGI; use DBI; my $q = new CGI; ### phone book database # CREATE TABLE `phonebook` ( # `login` varchar(10) NOT NULL, # `fullname` varchar(200) NOT NULL, # `areacode` int(10) unsigned NOT NULL default '123', # `phone` varchar(7) NOT NULL # ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COMMENT='Users and phone numbers'; # my $exported_fx = sub { my $searchterm = shift; my $sql = qq< select login from phonebook where login like ? or fullname like ? >; my $dbh = DBI->connect('dbi:mysql:test:localhost','guestuser','guestp4ss'); my $sth = $dbh->prepare( $sql ); $sth->execute( $searchterm . '%', $searchterm . '%' ); # start off the div contents with select init my $html = qq!\n!; return($html); }; my $get_details = sub { my $login = shift; my $sql = qq< select * from phonebook where login = ? >; my $dbh = DBI->connect('dbi:mysql:test:localhost','guestuser','guestp4ss'); my $sth = $dbh->prepare( $sql ); $sth->execute( $login ); my $html = ""; my $row = $sth->fetch(); if ( defined $row ) { $html .= "Login: " . $row->[0] . "
"; $html .= "Full Name: " . $row->[1] . "
"; $html .= "Area Code: " . $row->[2] . "
"; $html .= "Phone: " . $row->[3] . "
"; } else { $html .= "No Such User $login\n"; } return($html); }; my $Show_Form = sub { my $html = ""; $html .= < CGI::Ajax Example Who are you searching for?
Start typing and matches will display in the select box.
Selecting a match will give you details. 

EOT $html .= dump_table(); $html .= <

Show Source
EOT return $html; }; sub dump_table { my $sql = qq< select login from phonebook >; my $dbh = DBI->connect('dbi:mysql:test:localhost','guestuser','guestp4ss'); my $sth = $dbh->prepare( $sql ); $sth->execute(); my $html = ""; while ( my $row = $sth->fetch() ) { $html .= ""; } $html .= "
Current Logins in DB
" . $row->[0] . "
"; return($html); } my $pjx = CGI::Ajax->new( search => $exported_fx, details => $get_details ); $pjx->JSDEBUG(1); $pjx->DEBUG(1); # not show the html, which will include the embedded javascript code # to handle the ajax interaction print $pjx->build_html($q,$Show_Form); # this outputs the html for the page