MedMatrix
MedMatrix

Reputation: 336

How do autocomplete() works?

When I try to implement auto-complete using the code below I get nothing (no result, no error):

$('#keyword').autocomplete({
    source : '/Dev/pages/search.php',
    minLength : 3,
    type : 'POST',
    select: function( event, ui )
    {
         $(this).data("autocomplete").menu.element.addClass("yellow");
    }
})
.data( "ui-autocomplete" )._renderItem = function( ul, item )
{
    console.log(item);
    return $( "<li>" )
    .append( "<a>" + add3Dots(item.name,20) + "</a>" )
    .appendTo( ul );
 };

if(isset($_POST['term'])) {
        //Word enter by user
        $q = htmlentities($_POST['term']);

        $search = connection::bdd_test();
        $query = "SELECT name from BDD_TEST.companies WHERE name LIKE '%".$q."%' ORDER BY name asc";

        $result = $search->query($query);

        while($data = $result->fetch(PDO::FETCH_ASSOC)) {
           $data['name'];
        }    
}
else 
{
    $data['call']=false;
    $data['message']="Problem to collect word";

}


echo json_encode($data);

Can anyone tell me what's going wrong?

I think it could be data(), but i'm not sure.

Upvotes: 0

Views: 1016

Answers (1)

Murad Hasan
Murad Hasan

Reputation: 9583

PHP - search.php

$a_json = array();
$a_json_row = array();

$search = connection::bdd_test();
$query = "SELECT name from BDD_TEST.companies ORDER BY name asc";

$result = $search->query($query);
while($data = $result->fetch(PDO::FETCH_ASSOC)) {
    $a_json_row["name"] = $data['name'];
    array_push($a_json, $a_json_row);       
}
$json = json_encode($a_json);
print_r($json);

jQuery-ui Autocomplete

$( "#keyword" ).autocomplete({
  source: "/Dev/pages/search.php",
  minLength: 3,
  select: function( event, ui ) {
    $(this).data("autocomplete").menu.element.addClass("yellow");
  }
});

Make sure something:

  1. your data connection is ok or not.
  2. source is valid or not.

I think if everything is okey, then the code will work fine.

Upvotes: 1

Related Questions