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 *


Scroll to Top