Please take a look on the official documentation: https://select2.org/data-sources/ajax
You need to have a function which will handle the Request parameters and another function which handles the Response data.
Have you tried this?
How to use Select2 with JSON via Ajax request?
EDIT:
I created here a JSFIddle with your code: https://jsfiddle.net/7bdeo38c/6/
HTML:
<select class="js-example-basic-single" name="state"></select>
JS:
$(document).ready(function() {
$('.js-example-basic-single').select2(
{
ajax: {
url: 'https://jsonplaceholder.typicode.com/todos',
dataType: 'json',
data: function (params) {
return {
q: params.term // search term
};
},
processResults: function (data) {
return {
results: data // results
};
}
},
templateResult: formatResults, // Controls how the dropdown looks
templateSelection: formatSelection, // Controls what is displayed after selecting an item
escapeMarkup: function (m) { return m; }, // Let our custom formatter work
}
);
});
function formatResults (data) {
if (data.loading) {
return data.text;
}
var result;
if (data.completed) {
result = "<div class='select2-result-repository__description'>" + data.title + "</div>";
}
return result;
}
function formatSelection (data) {
return data.id + ' - ' + data.title || data.text;
}
A similar example exists in the official Select2 documentation. See the end of the Ajax chapter for the full code of the GitHub repositories example.
https://select2.org/data-sources/ajax