Select2 Ajax results could not be loaded

3.5k views Asked by At

Whenever I try to search for result in my select2 ajax searchbar I receive the following message:

'The results could not be loaded'

Html:

<select class="js-data-example-ajax form-control" multiple="multiple"></select>

Javascript:

$('select').each(function(idx, ele) {
            $(ele).select2({
                theme: 'bootstrap4',
                placeholder: ele.getAttribute('placeholder'),
                ajax: {
                    url: '/product/api/search',
                    dataType: 'json' },
                    type: 'GET',
            });
        });

I think that my Ajax settings are wrong could you assist?

1

There are 1 answers

5
daremachine On

Your code should look like this. No GET method needed.

$('select').each(function(idx, ele) {
  $(ele).select2({
      ajax: {
        url: 'https://api.github.com/search/repositories',
        dataType: 'json'
        // Additional AJAX parameters
      }
   }
});

Also your problem might be in your source json format because select2 need own format with results.

In order to accomplish this, Select2 expects a very specific data format. This format consists of a JSON object containing an array of objects keyed by the results key.

{
  "results": [
    {
      "id": 1,
      "text": "Option 1"
    },
    {
      "id": 2,
      "text": "Option 2"
    }
}

Also you can use processResults or transform data into certain format.