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 professionals since 2007

Our laser focus on a single technology has made us a leader in this space. Need help?

  • We build a solid first version of your product
  • We train your development team
  • We rescue your project in trouble
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)