-1

I use autocomplete to achieve a Google like search where the search suggestions are in a dropdown while i type what i'm searching for.

The Output of my code

enter image description here

HTML

    <td width="155"  bgcolor="#999999">Client Name</td>
    <td width="218" bgcolor="#999999"><input type="text" name="clientname" id="clientname" class="forinput" /></td>

script

   <script type="text/javascript">
      $(document).ready(function() {
  $( "#clientname" ).autocomplete(
   {
     source:"getautocomplete.php",
     minLength:1
    })
       });
    </script>

getautocomplete.php

  ..databaseconnection
  $term = trim(strip_tags($_GET['term']));//retrieve the search term that autocomplete sends

  $qstring = "SELECT clientname FROM client WHERE clientname LIKE '%".$term."%'";
  $result = mysql_query($qstring);//query the database for entries containing the term

  while ($row = mysql_fetch_array($result,MYSQL_ASSOC))//loop through the retrieved values
   {
    $row['clientname']=htmlentities(stripslashes($row['clientname']));
    $row_set[] = $row;//build an array
   }
   echo json_encode($row_set);//format the array into json data

What i want to achieve
enter image description here

I check my database connection and its correct. Can anybody explain to me what I'm doing wrong? did i missed something?

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • 1
    You need to debug this and provide more specifics. Are you watching your browser's console (F12)? In the Network tab, can you see the AJAX requests to getautocomplete.php taking place? Is the `term` being sent? – Michael Berkowski Jun 22 '14 at 02:17
  • See also [How can I prevent SQL injection in PHP](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). Your query is vulnerable to injection, since `$term` is unescaped. – Michael Berkowski Jun 22 '14 at 02:17
  • Also make sure on the PHP side that you have error reporting enabled and turned up. `error_reporting(E_ALL); ini_set('display_errors', 1)`; – Michael Berkowski Jun 22 '14 at 02:19

1 Answers1

1

I don't think the result you are sending back is valid according to what jQueryUI is expecting.

Now you are building an array of arrays and you should only send the values back (assuming that the label and the value are the same, the name of the client):

// $row['clientname']=htmlentities(stripslashes($row['clientname']));
$row_set[] = htmlentities(stripslashes($row['clientname']));    //build an array

Also note the comments about the deprecated mysql_* functions and sql injection.

jeroen
  • 91,079
  • 21
  • 114
  • 132