1

I am returning a JSON encoded array: echo(json_encode($data)); from php and I would like it to populate the suggest box from JQuery autocomplete. I'm using this:

$("#field").autocomplete({
            source : "SearchTest.php",
            maxLength: 5
        });

Not sure why this isn't working. After every key press, I would retrieve data and fill the suggest box with that data, I don't want autocomplete to sort and choose for me, I'm doing that server side. It's just a list of strings for now. Being able to customize how the data is presented would be nice as well.

Edit: Changed source to post:

$("#field").autocomplete({
            source : function(request, response) {
                $.post("SearchTest.php", request, response);
            },
            maxLength : 5
        });

Getting this error now:

Uncaught TypeError: Cannot use 'in' operator to search for '1240' in 
Notice: Undefined index: field in /.../SearchTest.php on line 25

Line 25 is : $whatTheyWantToSearch = $_POST['field'];

3
  • What error do you get? Can you paste your PHP code, your JS code seems Ok. Commented Jul 20, 2013 at 17:16
  • No errors. I just realized I'm not sending anything to the SearchTest.php. How would I post to the server and retrieve the JSON to populate the autocomplete? Commented Jul 20, 2013 at 17:21
  • Could you show me your php code? Commented Jul 20, 2013 at 17:22

5 Answers 5

4

Try using ajax

var searchRequest = null;
$("#field").autocomplete({
    maxLength: 5,
    source: function(request, response) {
        if (searchRequest !== null) {
            searchRequest.abort();
        }
        searchRequest = $.ajax({
            url: 'SearchTest.php',
            method: 'post',
            dataType: "json",
            data: {term: request.term},
            success: function(data) {
                searchRequest = null;
                response($.map(data.items, function(item) {
                    return {
                        value: item.name,
                        label: item.name
                    };
                }));
            }
        }).fail(function() {
            searchRequest = null;
        });
    }
});

JSON Response Example in SearchTest.php

<?php
header('Content-type: application/json');
echo '{"items":[{"name":"Ashok"},{"name":"Rai"},{"name":"Vinod"}]}';
?>

Demo Fiddle

Remote JSONP Demo

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

14 Comments

Keeps going to .fail function
That means response is not in proper JSON format from SearchTest.php, Answer updated, added method: 'post', JSON format and Demo Fiddle
I even tried echo '{"items":[{"name":"Ashok"},{"name":"Rai"},{"name":"Vinod"}]}'; on the php side, but still nothing.
Also this: $json = '{"items":[{"name":"Ashok"},{"name":"Rai"},{"name":"Vinod"}]}'; echo json_decode($json);
Before echo add content type to json by adding header('Content-type: application/json'); and make sure there is no echo, white space or plan text before header function
|
3

the proper json format for this from php:

<?php
   echo '[ {"name1":"val1"},{"name2":"val2"} ]'; 
?>

From js wich means []-array of {} objects.

In my case for autocomlete widjet this works fine:

    $response="[";
    while($row = $res->fetch_assoc()){
        if($response !="[")$response.=",";
        $response.='{"label":"'.$row["fio"].'","value":"'.$row["id"].'"}';
    }
    $response.="]";

    echo $response;

Comments

1

Maybe something wrong with the source parameter. Should it be '/Searchtest.php'?

http://api.jqueryui.com/autocomplete/#option-source

Comments

0

Somthing like this is the best way. json_encode do all work for you.

    $result = $_mysqli->query(...);
    $rs = array();
    $pos = 0;
    while($row = $result->fetch_assoc()){
        $rs[$pos]["n1"] = $row["n1"];
        $rs[$pos]["n2"] = $row["n2"];
        ...
        $rs[$pos++]["nn"] = $row["nn"];

    }
    header('Content-type: application/json');
    echo json_encode($rs);

Comments

0

The key to this solution is: We need to use item.label name because the AJAX will return the value in list format so we need to extract the value as shown in the below example. Please let me know if this solution works?

<html>
    <head>
            <title>Ajax</title>
            <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
            <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
            <script>
                 $(function() { 
                    $("#myname").autocomplete({
                      source: 'emp.php',
                      select: function (event, ui) {
                        $("#myname").val(ui.item.label);
                        $("#myid").val(ui.item.id);
                    },
                       minLength: 0,
                       autoFocus: true,
                    }); 
                });
            </script>
    </head>
    <body>
        <h2>Ajax Testing</h2>
        <input  name="myname" id="myname" type="text">
        <input  name="myid" id="myid" type="text">
    </body>
</html>
-------------- Below is the code of PHP for emp.php page --------------------------
<?php
require_once 'connection.php';
$query  = "SELECT myname as label , myid as id  FROM emp WHERE name LIKE ? ORDER BY name";
$rsTable = sqlsrv_query($conn, $query,array('%'.$_REQUEST['term'].'%'));
while ($row_rsTable = sqlsrv_fetch_array($rsTable, SQLSRV_FETCH_ASSOC)) {

    $emparray[] = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $row_rsTable);
}
echo json_encode($emparray);
sqlsrv_close($conn);
?>

1 Comment

Please don't post only code as an answer, but also provide an explanation of what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes

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.