Christian Kolb
Christian Kolb

Reputation: 1388

jQuery autocomplete json source - Does not autocomplete, but just show the full list

I use the autocomplete function of jQuery UI.

$("#search").autocomplete({
minLength: 0,
source: 'source.php',
select: function( event, ui ) {
    $("#search").val(ui.item.label);
    return false;
},
focus: function(event, ui) {
    $("#search").val(ui.item.label);
    return false;
}

});

I insert multiple elements in the source.php and return them json encoded.

$search[] = array(
   'value' => $id,
   'label' => $name
);
echo json_encode($search);

When I start typing into the autocomplete field a list is shown with the elements of the source.php. But unfortunately with all of them. They are not filtert depending on what I enter in the field.

Is there any special option I have to set when I work with json?

EDIT: Thanks to T.J. Crowder I came up with this solution to let jQuery do the job ; )

$.getJSON('source.php', function(search) {
    $("#search").autocomplete({
    minLength: 0,
    source: search,
    select: function( event, ui ) {
       $("#search").val(ui.item.label);
       return false;
    },
    focus: function(event, ui) {
        $("#search").val(ui.item.label);
        return false;
    }
});

Upvotes: 3

Views: 2819

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074168

It's not obvious from the docs, but when you supply anything as source that will involve running your code (either server- or client-side), the jQuery UI autocompleter expects you to filter the result. In the case of server-side code, you'd use the term parameter it passes to your PHP file. From the docs:

When a String is used, the Autocomplete plugin expects that string to point to a URL resource that will return JSON data. It can be on the same host or on a different one (must provide JSONP). The request parameter "term" gets added to that URL. The data itself can be in the same format as the local data described above.

(It would be good if they actually mentioned filtering there; I've logged an issue suggesting that they do. Update: It took them less than three hours to update the docs and close the issue; new docs will be pushed at some point, at least by v1.9. Nice!)

The autocompleter allows you to supply sources in three ways:

  • Static source array: In this case, the autocompleter does the filtering.

  • Server-side call: In this case, it passes a term argument and you're expected to use it to filter.

  • Client-side call: In this case, it passes a request object to your client-side code that has a term property; you're expected to use that to filter.

Upvotes: 2

Related Questions