How to load select2 options with remote data via AJAX

select2 is a powerful drop-down library for jQuery with many features. It supports remote data source via ajax property.

All parameters in ajax property of select2 will be directly passed to jQuery’s $.ajax function.

To use the following codes, you need to include select2 and jQuery first.

The server-side file which receives AJAX request needs to response with an array of objects. Here is an example

[{'id': 1, 'username': 'mark'}, {'id': 2, 'username': 'john'}]

HTML

<select name="filter" id="filter"  class="select2"  multiple="multiple" >
</select>

Script

$('.select2').select2({
        placeholder: ' Users',
        ajax: {
            url: [AJAX_URL],
            dataType: 'json',
            type: 'GET',
            data: function (term) {
                return {
                    term: term
                };
            },
            processResults: function (data) {
                return {
                    results: $.map(data, function (item) {
                        return {
                            text: item.username,
                            id: item.username
                        }
                    })
                };
            }
        }
    });

Leave a Comment

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close