Add additional data to the ajax request called when Select2 is opened

I am trying to send some additional data back as a query in the ajax request when the ‘select2:open’ event is called on my Select2 dropdown. Is there a way that I can manipulate what is sent back in this request? All my attempts so far have failed as I end up trying to re-initialise Select2 from within this event:

$(document).on('select2:open', '.s2mutex.keychar', function (e) {

    console.log(e);

    let values = [];

    $('#' + kcPrefix + '-forms').find('option:selected').each(function () {

        if ($(this).val() !== '') {

            values.push(parseInt($(this).val()));

        }

    });

    function formatResult(item) {

        return item.text;

    }

    function formatSelection(item) {

        return item.text;

    }

    $('.s2mutex.keychar').select2({

        ajax: {

            url: "/dashboard/keycharacteristic-autocomplete/",

            dataType: 'json',

            data: function (params) {

                return {

                    q: params.term,

                    selected: values

                };

            },

            processResults: function (data) {

                return {

                    results: data.results

                };

            }

        },

        templateResult: formatResult,

        templateSelection: formatSelection

    });

});

This doesn’t work I’m pretty sure for the reason I mentioned above. But is there a way I can do what I am trying to do in this ‘select2:open’ event?

I’m a little confused - so you want to send some information about the items that have already been selected, in subsequent AJAX requests?

Yes that is what I am trying to do, capture the ids of the already selected items from other selects and send them back in the ajax request of the current select2 field that is being used.

Any reason why you can’t just do all of this in your data callback? Something like:

$('.s2mutex.keychar').select2({
    ajax: {
        url: "/dashboard/keycharacteristic-autocomplete/",
        dataType: 'json',
        data: function (params) {
            var values = [];
            $('#' + kcPrefix + '-forms').find('option:selected').each(function () {
                if ($(this).val() !== '') {
                    values.push(parseInt($(this).val()));
                }
            });

            return {
                q: params.term,
                selected: values
            };
        },
        processResults: function (data) {
            return {
                results: data.results
            };
        }
    }
});

Then there is no need to listen for the select2:open event at all.

Yeah this is exactly what I ended up doing!