phpjqueryajaxjquery-uijquery-ui-autocomplete

jQuery autocomplete displays ID instead of name


so I have this jQuery script which fetches content from a database, and it needs to show the product name (my table has productid and productname). But instead of showing the product name, it shows the product Id. How can I fix this ?

Here's the jQuery code :-

<script>
  $(function() {
    function log( message ) {
      $( "<div>" ).text( message ).prependTo( "#log" );
      $( "#log" ).scrollTop( 0 );
    }

    $( "#birds" ).autocomplete({
      source: "search.php",
      minLength: 2,
      select: function( event, ui ) {


        log( ui.item ? "Selected: " + ui.item.actor + " aka " + ui.item.label :
          "Nothing selected, input was " + this.actor );
       // window.location.href = 'pretravel.php?id=' + ui.item.label;
       // document.testForm.action = "pretravel.php?id="+ui.item.value;
        //document.testForm.submit();
      }
    });
  });



  </script>

Here's the search.php

<?php
include 'dbconnector.php';

// Sanitise GET var
if(isset($_GET['term']))
{
$term = mysql_real_escape_string($_GET['term']);
// Add WHERE clause
//$term="Apple";
$query = "SELECT `productid`, `productname` FROM `products` WHERE `productname` LIKE '%".$term."%' ORDER BY `productid`";


$result = mysql_query($query,$db) or die (mysql_error($db));
$id=0;
$return=array();
while($row = mysql_fetch_array($result)){

    array_push($return,array('label'=>$row['productid'],'actor'=>$row['productname']));
    //array_push($return,array('actor'=>$row['productname'],'label'=>$row['productid']));

}

header('Content-type: application/json');
echo json_encode($return);
//var_dump($return);

exit(); // AJAX call, we don't want anything carrying on here
}
else
{
    header('Location:index');
}

?>

Any suggestions are welcome.


Solution

  • It would look like you are returning an Array, from the jQuery API reference the array type definition states An array of objects with label and value properties

    So if you change your search.php page to return these types it should work:

    while($row = mysql_fetch_array($result))
    {
       array_push($return,array('value'=>$row['productid'],'label'=>$row['productname']));
    }