Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding and implementing jQuery autocomplete with AJAX source and appendTo

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.

like image 1000
Ricky Mason Avatar asked Jul 30 '12 21:07

Ricky Mason


People also ask

How does autocomplete work in jQuery?

In the process of searching a specific value, the jQuery UI autocomplete selection feature provides the user with some string suggestions for the input area which effectively saves time. The autocomplete select action is triggered when the user selects one of the options from the pre-populated list.

What is autocomplete in Ajax?

Autocomplete feature is used to provide the auto suggestion for users while entering input. In this tutorial, we are going to suggest country names for the users based on the keyword they entered into the input field by using jQuery AJAX. jQuery Autocomplete function is called on the key-up event of the input field.

How can create autocomplete search box in jQuery?

Syntax: $("TagId"). autocomplete({ source : itemList // List of Words. })

How display image in jQuery ui autocomplete textbox in PHP?

Here we will make autocomplete textbox, in which make list pre-populated search result with image. This feature we will make by add custom html tag in jQuery UI autocomplete method by add _renderItem. Here we will use __renderItem method, by using this method we will add custom HTML code in autocomplete textbox.


1 Answers

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:

  • Custom data and display
  • Remote JSONP data source
like image 133
Andrew Whitaker Avatar answered Oct 11 '22 10:10

Andrew Whitaker