1

I am trying to modify this example of jQuery UI to accept the 2-dimensional JSON data. http://jqueryui.com/demos/autocomplete/#remote-with-cache

    var cache = {}, lastXhr;
    $( "#birds" ).autocomplete({
        minLength: 2,
        source: function( request, response ) {
            var term = request.term;
            if ( term in cache ) {
                response( cache[ term ] );
                return;
            }

            lastXhr = $.getJSON( "search.php", request, function( data, status, xhr ) {
                cache[ term ] = data;
                if ( xhr === lastXhr ) {
                    response( data );
                }
            });
        }
    });

How would I modify this to use the 'name' value in JSON data like this:

[{"name":"TEST1","slug":"blah-blah"},{"name":"TEST","slug":"example-slug-here"}]

1 Answer 1

5

The autocomplete widget expects data in the following format:

The local data can be a simple Array of Strings, or it contains Objects for each item in the array, with either a label or value property or both. The label property is displayed in the suggestion menu. The value will be inserted into the input element after the user selected something from the menu. If just one property is specified, it will be used for both

(emphasis mine)

This doesn't mean you can't use a remote source that doesn't respond with that format; you can massage the data to fit those requirements before calling the supplied response function.

With that in mind, I would modify the example for your case as follows:

lastXhr = $.getJSON( "search.php", request, function( data, status, xhr ) {
    cache[ term ] = $.map(data, function(item) {
        return {
            label: item.name,
            value: item.name,
            slug: item.slug,
            name: item.name
        };
    });
    if ( xhr === lastXhr ) {
        response( data );
    }
});

This should make the results show up properly (and caching should still work just fine). For another example of this, check out the remote JSONP example.

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

1 Comment

To anyone referencing this and having a problem where the autocomplete doesn't load the first time, only after deleting and typing again, change the last bit to this, because the mapped data is only being saved in the cache variable: if ( xhr === lastXhr ) { response( cache[ term ] ); }

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.