SKSK SKSK - 3 months ago 27
PHP Question

Autocomplete Jquery get id and name

I'm new into all this and need some help getting the id and the name of a game from my database with autocomplete

Everything works except, I can't get the id.

I have a get_games.php which looks like this

while ($row = mysql_fetch_assoc($data))
{
$results[$row['id']] = $row['title'];
}

echo json_encode($results);


My Jquery

<script>
$(function() {
$( "#games" ).autocomplete({
source: 'get_games.php',
select: function( event, ui ) {
$( "#id" ).val( ui.item.id );
return false;
}
});
});
</script>


Html

<input id="games" />
<input id="id" />


I see all the titles in the games input but no id.

Answer

Generate object array with properties value (id value) and label(title value) and later get it using ui.item.value.

PHP :

while ($row = mysql_fetch_assoc($data))
{        
    $results[] =  array(
         'label' => $row['title'],
         'value' => $row['id'],
        );
}

echo json_encode($results);

JQuery :

$(function() {
   $( "#games" ).autocomplete({
      source: 'get_games.php',
      select: function( event, ui ) {
        $( "#id" ).val( ui.item.value );
        return false;
      }
   });
});