What does autocomplete request/server response look like?

Pete Alvin picture Pete Alvin · Feb 22, 2011 · Viewed 86.7k times · Source

This seems to be a black hole: After an hour of searching the jQuery UI website, Stack Overflow, and googling, I've yet to find the most basic information of how to write the server side of the AutoComplete.

What parameter is passed to the server and what should the JSON response look like?

I must be missing something, because how did everyone else learn how to do this? Sites only seem to discuss the client-side JavaScript code and never the protocol or server-side examples.

I need enough to get the simplest remote example working.

Answer

Andrew Whitaker picture Andrew Whitaker · Feb 22, 2011

What parameter is passed to the server

You need to pass request.term to your server-side code (from the documentation):

A request object, with a single property called "term", which refers to the value currently in the text input.

Basically, in your autocomplete code, you'll have something like this:

$("#autocomplete").autocomplete({
    // request.term needs to be passed up to the server.
    source: function(request, response) { ... }
});

and what should the JSON response look like?

The autocomplete widget expects an array of JSON objects with label and value properties (although if you just specify value, it will be used as the label). So in the simplest case, you can just return data that looks like this:

[
    { label: 'C++', value: 'C++' }, 
    { label: 'Java', value: 'Java' }
    { label: 'COBOL', value: 'COBOL' }
]

If you need something more complicated, you can use the success argument of the $.ajax function to normalize the data you get back before the autocomplete gets it:

source: function( request, response ) {
    $.ajax({
        /* Snip */
        success: function(data) {
            response($.map( data.geonames, function( item ) {
                return {
                    label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
                    value: item.name
                }
            }));
         }
    });

This code is taken from the example here (This is a good example overall of ajax + autocomplete works in a more complex scenario).

Basically, what's going is that upon a successful ajax request, the data received is being normalized (using $.map) to what the autocomplete widget expects.

Hope that helps.