Understanding and implementing jQuery autocomplete with AJAX source and appendTo
Asked Answered
R

1

14

Below is my attempt at getting appendTo to work with jQuery autocomplete with AJAX source.

I have multiple questions, which will hopefully help many others who are struggling with understanding the correct way to implement autocomplete with and AJAX source.

1) source: function(request, response) {...} What does this do? Why is it needed.

2) What format does function(data){ response($.map (data, function(obj) { return the data in? I realize the data is in JSON format, but what is the point of .map? Is it necessary to do this? Are there benefits?

3a) When using appendTo and renderItem, is it necessary to have the above mentioned success data returned?

3b) Either or, depending on the above data, how do you correctly use appendTo and renderItem to change the formatting and display of your retrieved values?

$(function() {
$( ".find_group_ac" ).autocomplete({
        minLength: 1,
        source: function(request, response) {
            $.ajax({
                url: "welcome/search/",
                data: { term: $(".find_group_ac").val()},
                dataType: "json",
                type: "POST",
                success: function(data){ response($.map
                        (data, function(obj) {
                            return {
                            label: obj.name + ': ' + obj.description,
                            value: obj.name,
                            id: obj.name
                };}));}
            });
        }
    }).data( "autocomplete" )._renderItem = function( ul, item ) {
            return $( "<li></li>" )
                .data( "item.autocomplete", item )
                .append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
                .appendTo( ul );
        };
});

This might seem like a lot to answer, but I'm sure it will be valuable to many javascript newbies and certainly myself.

Ripen answered 30/7, 2012 at 21:6 Comment(0)
R
33

source: function(request, response) {...} What does this do? Why is it needed.

Since you're doing a custom AJAX POST to get the data, you must specify a function that calls the response callback with the desired autocomplete candidates.

In the simplest use case, you can just supply a string to the source parameter, and the widget will issue a GET request against that URL with an appended ?term=(term). Since you're doing a POST and sending up a different term, you must use the function version of source.

PS: You should supply the $.ajax call with request.term instead of $(".find_group_ac").val()


What format does function(data){ response($.map (data, function(obj) { return the data in? I realize the data is in JSON format, but what is the point of .map? Is it necessary to do this? Are there benefits?

The autocomplete widget expects an array data source who's items meet one of the following requirements:

  1. The item must be a single string, or:
  2. The item must be an object with a label property, a value, property, or both.

With this in mind, if you're using a server-side resource whose JSON is not formatted in this way, you have to transform the data to meet those specifications before supplying it to the response function. The common way to do this is to use $.map, which iterates over an array and transforms each element.


When using appendTo and renderItem, is it necessary to have the above mentioned success data returned?

No, but they are often used together.

Say you have an extra property (like description) that you want to display in the candidate list. In this case, you might transform the server-side result into the format autocomplete expects (to include label and value but still include description), but you also want to display the description property. In this case, you'll need to overload _renderItem.


Either or, depending on the above data, how do you correctly use appendTo and renderItem to change the formatting and display of your retrieved values?

If the questions asked above this ones are answered adequately in this answer, then all I should need to do is post some code that brings the concepts together:

$( ".find_group_ac" ).autocomplete({
    minLength: 1,
    source: function(request, response) {
        $.ajax({
            url: "welcome/search/",
            data: { term: $(".find_group_ac").val()},
            dataType: "json",
            type: "POST",
            success: function(data) { 
                response($.map(data, function(obj) {
                    return {
                        label: obj.name,
                        value: obj.name,
                        description: obj.description,
                        id: obj.name // don't really need this unless you're using it elsewhere.
                    };
                }));
            }

        });
    }
}).data( "autocomplete" )._renderItem = function( ul, item ) {
    // Inside of _renderItem you can use any property that exists on each item that we built
    // with $.map above */
    return $("<li></li>")
        .data("item.autocomplete", item)
        .append("<a>" + item.label + "<br>" + item.description + "</a>")
        .appendTo(ul);
};

The examples on jQueryUI's documentation page for autocomplete are actually quite extensive and could be helpful. Specifically, be sure to check out:

Runstadler answered 30/7, 2012 at 21:38 Comment(1)
Thanks for this snippet. Please note that a comma (,) is missing after description: obj.descriptionPloughboy

© 2022 - 2024 — McMap. All rights reserved.