Howto: Select2 with AJAX

Posted . Visible to the public.

Select2 comes with AJAX support built in, using jQuery's AJAX methods.
...
For remote data sources only, Select2 does not create a new element until the item has been selected for the first time. This is done for performance reasons. Once an has been created, it will remain in the DOM even if the selection is later changed.

If you have a huge collection of records for your select2 input, you can populate it via AJAX in order to not pollute your HTML with lots of <option> elements.

All you have to do is to provide the collection in the Select2 data format and extend the input with ajax options. You should paginate your results on server side to reduce the load. Select2 supports an "infinite scroll" feature, which will be enabled with a params.page property in the request and a pagination.more value in the response.

I would also recommend to use the minimumInputLength option to not fire your first request on opening the input element.

The Select2 data format

{
  "results": [
    {
      "id": 1,
      "text": "Option 1"
    },
    {
      "id": 2,
      "text": "Option 2"
    }
  ],
  "pagination": {
    "more": true
  }
}

Basic ajax options

$('#mySelect2').select2({
  ajax: {
    url: <url-to-your-source>,
    data: function (params) {
      return {
        query: params.term,
        page: params.page || 1
      }
    }
    processResults: function (data, params) {
      return data
    },
  }
});

Further reading: https://select2.org/data-sources/ajax Show archive.org snapshot

Florian Leinsinger
Last edit
Florian Leinsinger
License
Source code in this card is licensed under the MIT License.
Posted by Florian Leinsinger to makandra dev (2020-07-03 10:43)