How to Insert Options with Ajax while Having Option Group

I have a multiselect dropdown with below data:

var fruitArray = [];
var fruitGreen = [];
var fruitNotGreen = [];

fruitGreen = {
“text”: “Green”,
“children”: [
{ “id”: “Watermelon”, “text”: “Watermelon” },
{ “id”: “Lime”, “text”: “Lime” },
{ “id”: “Guava”, “text”: “Guava” },
{ “id”: “Avocado”, “text”: “Avocado” },
{ “id”: “Kiwi”, “text”: “Kiwi” },
]};
fruitNotGreen = {
“text”: “Not Green”,
“children”: [
{ “id”: “Apple”, “text”: “Apple” },
{ “id”: “Orange”, “text”: “Orange” },
{ “id”: “Berries”, “text”: “Berries” },
{ “id”: “Grape”, “text”: “Grape” },
{ “id”: “Pineapple”, “text”: “Pineapple” },
]};
fruitArray.push(fruitGreen, fruitNotGreen);

$(’.select2’).select2({
placeholder: ‘-- Select Fruits --’,
allowClear: true,
maximumSelectionLength: 50,
dropdownAutoWidth: true,
data: fruitArray,
multiple: true,
closeOnSelect: false
});

How to Insert Options with Ajax while Having Option Group? Please help

Your example code does not use the built-in AJAX feature of Select2, and you have the initial data in an array (fruitArray in your example code). So when you mention AJAX, do you mean Select2’s built-in AJAX capability, or do you mean retrieving additional data via AJAX outside of the Select2 (e.g., using fetch(), XMLHttpRequest, jQuery.ajax(), or a third-party AJAX package like axios)?

If you can give me more details about what you want to do, I can help you figure out how to do it.