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);
?>
4
  • 1
    Are you sure it is ` $data[] = array( 'c++','Java','JavScript',"c#" );` and not ` $data = array( 'c++','Java','JavScript',"c#" );` Commented Jul 7, 2015 at 22:20
  • I actually had the [], just didn’t copy it over correctly. That didn’t work Commented Jul 7, 2015 at 22:35
  • And you can have it as $data = array( 'c++','Java','JavScript',"c#" ); BTW Commented Jul 7, 2015 at 22:41
  • I think your issue is in your javascript not handling correctly. See my answer below. Commented Jul 7, 2015 at 22:51

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

When i added $stmt = $dbh->prepare($query); $stmt->execute(array(ucfirst($_REQUEST['term']) . '%')); $data = array();. I wasn’t working
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);

7 Comments

It works, but it shows all the elements, instead of the elements that contain the same letters
Also tried $data = array( "value"=>'C++', "value"=>'Java', "value"=>'Javascript', "value"=>'C#' ); This only returned c# whenever i type in anything
That will never work. The value key will be overwritten every time and you will get only last value.
I think you need to perform search here.
Yes sure. Do you use database here? If you are retrieving data from database table then use similar query according to you. $term = trim(strip_tags($_GET['term'])); $qstring = "SELECT * FROM your_tbl WHERE language LIKE '%".$term."%'";
|
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
    })
}

3 Comments

Did you post your entire javascript handler?
Yup, maybe this cant be done by passing array by php
It can because I use it all the time. Your javascript is wrong. You're echoing a JSON string when autocomplete is looking for a javascript array.
0
<?php
    $data = array(
        'c++',
        'Java',
        'JavScript',"c#" );
echo json_encode($data);
?>

2 Comments

Nope, will return everything no matter what you type in
because this code return 4 values - You must write some PHP code to filter results :D
-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(); 

3 Comments

This is open to SQL injections and using the deprecated mysql_ functions.
Thanks for this , i would love some suggestions to make it better if you have any.
Start here: php.net/manual/en/book.mysqli.php and get to know it very well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.