I've coded all the components for the jQuery autocomplete widget, but I'm having some trouble getting it to work. This is what I've done so far:
1. Added the following links to my PHP page's head:
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/redmond/jquery-ui.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
2. Created the following function:
<script>
$(function()
{
$('#projNo0').autocomplete(
{
source: "projects.php",
minLength: 2,
select: function(event,ui)
{
$('#projNo0').val(ui.item.id);
}
});
});
</script>
3. Created a PHP backend called "projects.php" with the following query:
$return_arr = array();
if ($con)
{
$ac_term = "%".$_GET['term']."%";
$query = $con2->prepare("SELECT CodeIDf_2 FROM CostCenters
W
HERE Code
IDf_2 LIKE :term ORDER BY CodeIDf_2");
$data = array('term'=>$ac_term);
$query->execute($data);
/* Retrieve and store in array the results of the query.*/
while ($row = $query->fetch(PDO::FETCH_ASSOC))
{
$row_array['CodeIDf_2'] = $row['CodeIDf_2'];
array_push($return_arr,$row_array);
}
}
4. Created an HTML input field, thus:
<tr class="ui-widget">
<label for="projNo0"></label><input type="text" name="projNo[]" id="projNo0" value="<redacted>" />
</tr>
The above is part of an array of fields in a table, each with a unique ID (projNo0, projNo1, etc.).
I can confirm that the script in step 3 works. I'm able to echo the values of CodeIDf_2 if I remove the WHERE condition from the query. This is from a SQL Server database, not MySQL. Not sure if that makes a difference, but I'm guessing not.
After all of the above, my autocomplete field does not work. Nothing happens when I type into it. I'm pretty much a newbie when it comes to JQuery, so I don't know what I've missed. I would appreciate any guidance the community can offer.
Most of what I've learned came from this article: