omni
omni

Reputation: 35

How to use jquery autocomplete with server/sql data fetched with php?

Is there something wrong with this code?

Form input:

<input type="text" id="currentTag" name="currentTag" class="inputbox"/>

jquery:

$("#currentTag").autocomplete({
    source:'getautocomplete.php',
    minLength:1
});

getautocomplete.php

$term=$_GET["term"];
$query=mysql_query("SELECT * FROM table_name WHERE tag_value LIKE '%".$term."%' ORDER BY tag_value ");
$results=array();

while($row = mysql_fetch_array($query)){
    $results[] = array('label' => $row['tag_value']);
}
echo json_encode($results);

getautocomplete.php output when script is called directly:

[{"label":"birdseye"},{"label":"doggy"},{"label":"tomhat"}]

'SOLVED' It's a bit of a hack job, but I ended up setting source as a jquery var instead of url. Then used php include to echo the json into the var. All this in a Joomla site. Some conflict that I don't understand was happening, because the above code worked in a test file outside of Joomla. If anyone knows the conflict I'd curious to learn. Cheers.

$(document).ready(function() {
    $( "#currentTag" ).autocomplete({
        source: tags
    });
});
var tags = <?php include("getautocomplete.php");?>;

Upvotes: 0

Views: 2181

Answers (2)

sasi kanth
sasi kanth

Reputation: 2927

see this link http://jqueryui.com/autocomplete/

  1. Include all js .
  2. Get the data from MySQL using Ajax. Proceed With
  3. what you did now.

In the above link you will find demo source code see once

try this once

 $( "#currentTag" ).autocomplete({
source: function( request, response ) {
  $.ajax({
  url: "getautocomplete.php",
  dataType: "jsonp",
  data: {
 q: request.term
   },
   success: function( data ) {
  response( data );
   }
 });
 },
minLength: 3
  });

Upvotes: 1

DarkMukke
DarkMukke

Reputation: 2489

There is a few thing wrong here, it could be any of the problems

  • i assume you connect to the db first, this is not shown in the example but that might be the problem
  • you should make sure you escape your $term, because you give the availability of SQL injection
  • you should avoid useing SELECT * if you only need tag_value
  • you should use mysql_fetch_assoc if you want to use assoc arrays in your result
  • you should make sure the source URL is correct, it is a relative path the way you've put it, try to always use absolute paths, you never know where your script will be used (and with pretty urls, this becomes worse)

Upvotes: 0

Related Questions