I am trying to attach AJAX fetched value with Select2. My JavaScript code is like below.
(function($) {
$(document).ready(function() {
$(".volunteer").on("click", function (event) {
let element_id = event.target.id;
// Check if select is already loaded
if (!$(this).has("select").length) {
var cellEle = $(this);
// Populate select element
cellEle.html(`<select class="js-example-basic-multiple" multiple="multiple"></select>`);
// Initialise select2
let selectEle = cellEle.children("select").select2({
ajax: {
url: "/wordpressbosta/matt/wp-admin/admin-ajax.php",
dataType: 'json',
data: function (params) {
return {
q: element_id,
action: 'get_data'
};
},
type: "post",
processResults: function(data) {
var options = [];
if ( data ) {
$.each( data, function( index, text ) {
options.push( { text: text } );
});
}
return {
results: options
};
}
}
});
}
});
});
})(jQuery)
I am getting output like below.
If I click on any value, it is not set to the select box. Values are not working.
Select2 requires that each option has an id property and a text property. In the code above the processResults method is returning an array of objects which contain only a text property, without an id. When adding objects to the array in processResults an id should be included:
options.push({ id: id, text: text });
Details on this format can be found at https://select2.org/data-sources/formats. As per this page:
Blank
ids or anidwith a value of0are not permitted.
You could either use text as the id value if it's unique, or use index + 1 (+ 1 to avoid a value of 0). In the below example code text is used.
processResults: function(data) {
var options = [];
if (data) {
$.each(data, function (index, text) {
options.push({ id: text, text: text });
});
}
return {
results: options
};
}