I'm trying to get a jQuery autocomplete field to work with data from a remote DB, and I'm having no luck. Here's what I've attempted so far:
1.I have all of the necessary links to the source code in my header.
2.I have the following jQuery script written:
<script>
$(function() {
function log( message ) {
$( "<div>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 0 );
}
$( "#projNo0" ).autocomplete({ //projNo0 is the name of the autocomplete field
source: "projects.php",
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
}
});
});
</script>
3.This is the PHP backend that's supposed to populate the autocomplete field projNo0 (the DB connection is handled elsewhere in the same file):
$return_arr = array();
if ($con2) //If the DB connection is successful
{
//Get the user's input from projNo0
$ac_term = "%".$_GET['term']."%";
$query = $con2->prepare("SELECT CodeID FROM CodeTable WHERE
CodeID LIKE :term");
$data = array('term'=>$ac_term);
$query->execute($data);
while ($row = $query->fetch(PDO::FETCH_ASSOC))
{
$row_array['CodeID'] = $row['CodeID'];
array_push($return_arr,$row_array);
//echo $row['CodeID']; //line used for testing
//echo '<br />'; //line used for testing
}
}
4.And here is the HTML for my autocomplete field. It's part of an array:
<p class="ui-widget">
<input type="text" name="projNo[]" id="projNo0" value="<? php echo $projNo[0]; ?>" />
</p>
I can confirm that there's no problem connecting to the remote DB. I'm able to echo out the array of values the SELECT statement returns. The jQuery script only works, however, when I hardcode an array of values into it. (Replace source "projects.php" with ["Bob","Carol","Ted","Alice"], for example.) When I right-click on the field and inspect it, the network activity shows that projects.php is being called and that it's accepting my input, appending it as a GET variable. The status of that activity is "OK". But I get no drop-down list of autofill suggestions.
Where is the break between my application and the database? I'm assuming that's where the problem is, since the script works with hardcoded values.
echo json_encode(array_values($query->fetchAll(PDO::FETCH_COLUMN, 0)));using my own name as :term, I get ["Michael Benton"]. My name is in the database, so it's finding it okay. It's just not giving it to the JQuery script.