Persistent Old Data in Select2 Despite New AJAX Fetch

Hello, Select2 Community,

I’m encountering an issue with Select2 where the selected data does not update after fetching new (updated) data via AJAX, even though the dropdown options themselves are correctly updated and new data is received.

Here’s a brief overview of my setup:

I have a Select2 dropdown configured to fetch data from my server using AJAX. This part works perfectly; the dropdown dynamically updates with new options based on the AJAX response.

$('#Template').select2({
    placeholder: "Please select a Template",
    ajax: {
        url: '/search/templates',
        type: 'POST',
        dataType: 'json',
        data: function(params) {
            return {
                search: params.term,
                page: params.page
            };
        },
        processResults: function(data) {
            return {
                results: data.items,
                pagination: {
                    more: data.pagination.more
                }
            };
        }
    }
});

After that, a form gets populated based on the data received from the initial request. This also works perfectly as long as no updates are made.

However, the issue arises after making a selection and submitting a form that updates data on the server.

When I now reopen the Select2 dropdown, it successfully fetches the updated data from the server (confirmed via network inspection). However, when I attempt to access the selected data using $(’#Template’).select2(‘data’); within a select2:select event handler, it still returns the old data, not reflecting the update.

.on('select2:select', function(e) {
    var selectedData = $('#Template').select2('data');
    if (selectedData && selectedData.length > 0 && selectedData[0].data) {
        try {
            var dataObjects = JSON.parse(selectedData[0].data);
           // Here, dataObjects should reflect the newly selected data, but it's still old
        } catch (error) {
            console.error('Error parsing selected data:', error);
        }
    }
});