简体   繁体   中英

Jquery Autocomplete with PHP

I have been messing with this for too long trying to get it to work. Can anyone please see if you have any pointers.

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link type="text/css" rel="stylesheet" href="autocomplete.css" />      
        <script src="jquery-1.7.2.min.js" type="text/javascript"></script>
        <script src="jquery-ui-1.8.21.custom.min.js" type="text/javascript"></script>
        <title></title>
    </head>
    <body>
        <style>
            .ui-autocomplete-loading { background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat; }
        </style>
        <script>
            $(function() {                
                $( "#materials" ).autocomplete({
                    source: "autocomplete.php",
                    minLength: 2
                });
            });
        </script>
        <div class="demo">

            <div class="ui-widget">
                <label for="materials">Materials: </label>
                <input id="materials" />
            </div>
        </div><!-- End demo -->            
    </body>
</html>

and the php file is

require_once "db_con.php"; // Database connection, I know this works.
$q = strtolower($_GET["q"]);
if (!$q)
    return;

$sql = "SELECT * FROM materials WHERE name LIKE '%$q%'"; 
$rsd = mysqli_query($dbc, $sql) or die(mysqli_error($dbc));
while ($rs = mysqli_fetch_array($rsd)) {
    $cname = $rs['name']; // I know this all returns correctly
    echo json_encode($cname); // First time I have ever used json, error might be here.
}

I am trying to have a webpage with an autocomplete powered by Jquery that is supplied data from mysql using PHP. Simples. Only its not working...

Anyone have any ideas what I am missing ?

Regards

---- EDIT ----

In order to check this was working I completed the following:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link type="text/css" rel="stylesheet" href="autocomplete.css" />      
        <script src="jquery-1.7.2.min.js" type="text/javascript"></script>
        <script src="jquery-ui-1.8.21.custom.min.js" type="text/javascript"></script>
        <title></title>
    </head>
    <body>
        <style>
            .ui-autocomplete-loading { background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat; }
        </style>
        <script>
            $(function() {                
                $( "#materials" ).autocomplete({
                    source: <?php
include_once 'db_con.php';
$sql = "SELECT name FROM materials";
$rsd = mysqli_query($dbc, $sql) or die(mysqli_error($dbc));
echo '[';
while ($rs = mysqli_fetch_array($rsd)) {
    echo "'" . $rs['name'] . "', "; //add results to array
}
echo ']';
?>,
                        minLength: 2
                    });
                });
        </script>
        <div class="demo">

            <div class="ui-widget">
                <label for="materials">Materials: </label>
                <input id="materials" />
            </div>


        </div><!-- End demo -->        
    </body>
</html>

Which works perfectly. So good infact I think im going to keep this code not quite how its supposed to work but...

In the PHP part, maybe try something like that:

$res = array();  //create a new array
while ($rs = mysqli_fetch_array($rsd)) {
  $res[] = (string)$rs['name']; //add results to array, casted as string
}
header('Content-type: application/json'); //add JSON headers (might work w/o)
echo json_encode($res);  //output array as JSON

...that way you should have all results in one array like ['name1', 'name2', 'name3']

Try this code, Its works for me

$().ready(function() {
$("#materials").autocomplete("autocomplete.php", {
        width: 260,
        matchContains: true,
        autoFill:true,
        selectFirst: false
    });
});

to handle a json answer from a php ajax call i customize the source function and handle the result myself this way:

$(function() {                
    $( "#materials" ).autocomplete({
        source: function(request, response){
            $.post("autocomplete.php", {
                term: request.term
            }, function(data){
                if (data.length == 0) {
                    data.push({
                        label: "No result found",
                    });
                }
                response($.map(data, function(item){
                    return {
                        label: item.name,
                        value: item.name
                    }
                }))
            }, "json");
        },
        minLength: 2,
        dataType : "json"});
});

Your PHP is all wrong:

while ($rs = mysqli_fetch_array($rsd)) {
    $cname = $rs['name']; // I know this all returns correctly
    echo json_encode($cname); // First time I have ever used json, error might be here.
}

Should be:

$cname = array();
while ($rs = mysqli_fetch_array($rsd)) {
    $cname[]['label'] = $rs['name']; // I know this all returns correctly
    break;
}
echo json_encode($cname); // First time I have ever used json, error might be here.

label is the default label field within an array row that is used by jqueryautocomplete (I believe). Also the return must be an array of arrays each array row representing a match.

You can make it more complicated by adding a value field for what to make the textbox to actually equal to by doing:

$cname = array();
while ($rs = mysqli_fetch_array($rsd)) {
    $cname[]['label'] = $rs['name']; // I know this all returns correctly
    $cname[]['value'] = $rs['id'];
    break;
}
echo json_encode($cname); // First time I have ever used json, error might be here.

Of course I don't think your actually wanting the break; I put this in because:

while ($rs = mysqli_fetch_array($rsd)) {
    $cname = $rs['name']; // I know this all returns correctly
    echo json_encode($cname); // First time I have ever used json, error might be here.
}

Denotes to me that you are actually returning a single row from your results. If you are not and are actually returning all results then take the break; out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM