Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select2 - Fetch data from backend and add options to selectbox

I'm currently trying to get select2 to work, however, I'm struggling a little bit right now. What I want to achive, is fairly simple: I fetch a JSON from a webserver which consists out of key/value pairs (one ID to one string). After fetching those, I want to create options out of those and add them to select2 so they user can select one of them.

I kept as close to the code in the documentation as humanly possible:

$('#catSearchBox').select2({
    width: '500px',
    ajax: {
        url: "url/to/data",
        dataType: 'json',
        delay: 250,
        cache: false,
        data: function (params) {
            return {
                searchKey: params.term
            };
        },
        processResults: function (data, params) {
            $.each(data, function(catName, catId) {
                var newOption = new Option(catId, catName, false, false);
                $('#catSearchBox').append(newOption).trigger('change');
            });
        }
    },
    placeholder: 'Suche nach Kategorie ...',
    minimumInputLength: 3
});

Now, everything here works up until the append. When I search for anything, the options are generated correctly, however, the append seems to fail as no options are displayed at all. It looks like this:

select2 after search

However, it's not because of an empty or invalid response, because the options are definitely created:

option creation

I'm kinda at a loss here, I don't see why my code is not working, especially since I kept as close as possible to the code in the documentation (https://select2.org/data-sources/ajax and https://select2.org/programmatic-control/add-select-clear-items).

Does anyone have any idea on how to solve this problem? If you need any additional information I might have missed out, please let me know.

like image 674
Realitätsverlust Avatar asked Nov 22 '25 15:11

Realitätsverlust


1 Answers

processResults Is not used to append options to the select2. It is used to transform the response from the API. It should return a valid array of objects to feed select2.

Something like:

var newData = [];
$.each(data, function(catName, catId) {
    newData.push({ id: catId, text: catName });
});

return { results: newData };
like image 153
Alexander Dimitrov Avatar answered Nov 24 '25 04:11

Alexander Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!