i have the same problem like this https://stackoverflow.com/questions/39449293/how-to-configure-ajax-select2-for-working-with-a-barcode-scanner .
this is my code :
$("#kode-barang").select2({ ajax: { url: base_url + 'barang/kodebarang_autocom/', dataType: "json", delay: 0, data: function (params) { return { kode: params.term }; }, processResults: function (data) { var results = []; $.each(data, function (index, item) { results.push({ id: item.id_barang, text: item.kode_barang, }); }); return { results: results }; }, cache: true }, language: "id", theme: "bootstrap4", });