Skip to content
Advertisement

JQuery Autocomplete, populate 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 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'];

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement