Read more

Howto: Select2 with AJAX

Florian Leinsinger
July 03, 2020Software engineer at makandra GmbH

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.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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

Posted by Florian Leinsinger to makandra dev (2020-07-03 12:43)