2

So i just found out about the jquery auto complete and i would like to add it to my web-page. I want to hook it up to my php code so i can search my sql database. However Whenever i try to run my auto complete,it doesnt seem to find the php array im passing ( im just trying to get an array to work for now) . Can someone help?

Jquery Code

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery UI Autocomplete - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
  <script>
  $(function() {
    $( "#tags" ).autocomplete({
      source: "test.php"
    });
  });
  </script>
</head>
<body>

<div class="ui-widget">
  <label for="tags">Tags: </label>
  <input id="tags">
</div>


</body>
</html>

PHP code

<?php
    $data[] = array(
        'c++','Java','JavScript',"c#" );
echo json_encode($data);
?>
Andrew Kralovec
  • 491
  • 4
  • 13

5 Answers5

1

The array pattern used here should be as below.

<?php
$data = array(
    array("value"=>'C++'),
    array("value"=>'Java'),
    array("value"=>'Javascript'),
    array("value"=>'C#'),
);
echo json_encode($data);
Pratik Soni
  • 2,498
  • 16
  • 26
1

If you're using PHP >= 5.4:

$data = [
    [ 'value' => 'C++' ],
    [ 'value' => 'Java' ],
    [ 'value' => 'Javascript' ],
    [ 'value' => 'C#' ]
];
echo json_encode( $data );

Here's a working example of my autocomplete code:

function get_data(type, target, min_length )
{
    $(target).autocomplete({
        source: function( request, response ) {
            var submit = {
                term: request.term,
                type: type
            };
            $.ajax({
                url: '/request/get',
                data: { thisRequest: submit},
                dataType: "json",
                method: "post",
                success: function( data ) {
                    response($.map( data.Data, function( item ) {

                        return {
                            label: item.label,
                            value: item.label
                        }
                    }));
                }
            });
        },
        minLength: min_length
    })
}
visevo
  • 791
  • 7
  • 23
1

This is an updated version of your answer which should resolve the deprecated SQL driver and the injection issue. You need to replace the SECOND_COLUMNNAME with your actual column's name. Aside from that I think this should work.

<?php
try {
    $dbh = new PDO('mysql:host=localhost;dbname=DB','username','password');
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}
if(empty($_REQUEST['term']))
    exit();
//require_once('connect.php'); connection to db is in this file so connection is not needed
$query =  'SELECT name, SECOND_COLUMNNAME FROM locations 
        WHERE name 
        LIKE ?
        ORDER BY id ASC 
        LIMIT 0,10';
$stmt = $dbh->prepare($query);
$stmt->execute(array(ucfirst($_REQUEST['term']) . '%'));
$data = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $data[] = array(
                'label' => $row['name'],
                'value' => $row['SECOND_COLUMNNAME']
                );
}
echo json_encode($data);
flush();

Links:

http://php.net/manual/en/pdo.prepared-statements.php
http://php.net/manual/en/pdo.connections.php
https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
How can I prevent SQL injection in PHP?

Also not sure if there was anything else inside connect.php, you might need to bring that back.

Community
  • 1
  • 1
chris85
  • 23,846
  • 7
  • 34
  • 51
  • When i added $stmt = $dbh->prepare($query); $stmt->execute(array(ucfirst($_REQUEST['term']) . '%')); $data = array();. I wasn’t working – Andrew Kralovec Jul 08 '15 at 18:52
0
<?php
    $data = array(
        'c++',
        'Java',
        'JavScript',"c#" );
echo json_encode($data);
?>
ryrysz
  • 907
  • 5
  • 11
-1

So i want with Pratik Soni advice and did a search. Here is the php code if anyone wants to use it

<?php
// Connect to server and select databse.
$dblink = mysql_connect('localhost','username','password') or die(mysql_error());
mysql_select_db('DB');
?>

<?php
if(!isset($_REQUEST['term']))
exit();
require('connect.php');
  $term = 
  $query = mysql_query('
SELECT * FROM locations 
WHERE name 
LIKE "'.ucfirst($_REQUEST['term']).'%" 
ORDER BY id ASC 
LIMIT 0,10', $dblink
  );
  $data = array();
  while($row = mysql_fetch_array($query, MYSQL_ASSOC)){
        $data[] = array(
    'label' => $row['name'],
    'value' => $row['name'],
   );   
 }
 echo json_encode($data);
  flush(); 
Andrew Kralovec
  • 491
  • 4
  • 13