I am trying to implement Jquery Autocomplete. I'm using the tutorial example from their site but so far it is returning all of my results regardless of what I enter for the search
<script>
$(function() {
$( "#birds" ).autocomplete({
source: "fetchData.php",
minLength: 2,
select: function( event, ui ) {
log( "Selected: " ui.item.value " aka " ui.item.id );
}
});
});
fetchData.php
$conn = new PDO ('odbc:xxx','xxxx','xxxxxx');
$qry = "select distinct name_customer from v_customer_master";
$sql = $conn->query($qry);
//$custName = array();
while($row = $sql->fetch((PDO::FETCH_ASSOC))){
$row['name_customer'] = mb_convert_encoding($row['name_customer'], 'UTF-8', 'UTF-8');
$custName[] = $row['name_customer'];
//array_push($custName,$row['name_customer']);
}
echo json_encode($custName);
CodePudding user response:
I ended up finding a different solution using bootstrap. I copied a tutorial here after tailoring it to my needs I was able to get the typeahead/autocomplete I was looking for.
CodePudding user response:
According to network tab in DevTools - jQuery ui apparently sends to the url the parameter term
holding the search term. So you need is use that in your sql query. Also they expect array of {id: ..., value: ...} as input.
<?php
$conn = new PDO ('odbc:xxx','xxxx','xxxxxx');
$term = $_REQUEST["term"];
$escaped = $conn->quote($term);
$qry = "select distinct name_customer from v_customer_master where name_customer like '$escaped%' ";
$sql = $conn->query($qry);
$custName = array();
while($row = $sql->fetch((PDO::FETCH_ASSOC))){
$row['name_customer'] = mb_convert_encoding($row['name_customer'], 'UTF-8', 'UTF-8');
$custName[] = [
'id' => $row['name_customer'], // or actual id
'value' => $row['name_customer'],
];
}
echo json_encode($custName);
As you can see in the following snippet that the url is being blocked with the param term
.
$(function() {
$( "#birds" ).autocomplete({
source: "fetchData.php",
minLength: 2,
select: function( event, ui ) {
log( "Selected: " ui.item.value " aka " ui.item.id );
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
<input id="birds">
So the error is in the PHP or it's output. It's debugging and elimination time.