JQuery autocomplete, populated with data from pHp json

I am returning a JSON-encoded array: echo(json_encode($data));from php, and I would like it to populate a sentence field from JQuery autocomplete. I use this:

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

I don’t know why this is not working. After each keystroke, I get the data and fill in the proposal field with this data, I don’t want the autocomplete sorted and selected for me, I do this side of the server. This is currently a list of strings. Being able to customize how the data will be presented would be nice.

Edit: Changed source for publication:

$("#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: $whatTheyWantToSearch = $_POST['field'];

0
source share
4 answers

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;
        });
    }
});

Sample JSON response in SearchTest.php

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

Demo script

JSONP

+3

json php:

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

js, [] - {}.

widjet :

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

    echo $response;
+1

Maybe something is wrong with the original parameter. Should it be "/Searchtest.php"?

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

0
source

Something like this is the best way. json_encode everything works 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);
0
source

All Articles