...
my $main_tmpl = HTML::Template->new(filename => 'search.tmpl', die_on_bad_params => 1);
...
sub data {
my $id = shift || return;
my $sql = qq{SELECT distinct name, city, state
FROM my_table
WHERE name like ? order by name asc};
my $sth = $dbh->prepare($sql);
$sth->execute(${id}.'%') or die "SQL Error: $DBI::errstr\n";
my $all_data = $sth->fetchall_arrayref({});
my @loop_data = (); # initialize an array to hold loop
# Count things
my $c = 0; my @count;
foreach my $row (@{$all_data}) {
$c++;
my %row_data; # get a fresh hash for the row data
# fill in these rows
$row_data{NAME} = $row->{NAME} || '';
$row_data{CITY} = $row->{CITY} || '';
$row_data{STATE} = $row->{STATE} || '';
push @count, $c;
# the crucial step - push a reference to this row into the loop
push(@loop_data, \%row_data);
}
# Count things
my $counter = @count;
# I need to load the data here but it doesn't.
# load values into the template
$main_tmpl->param(
ALL_DATA => \@loop_data,
COUNT => $counter,
);
# If sending data through json use this
# This works if I use jQuery to process the returned json from here
# but I am trying to load the data using HTML::Template
=code
print $q->header(-type => "application/json");
if(@loop_data){
print to_json(\@loop_data);
exit;
}else{
my $json_string = [{ result => "No data"}];
print to_json($json_string);
exit;
}
=cut
} # end sub