How to populate the select2 after received the ajax response

I can populate the select2 but after I receive the response from ajax I need to click out of select2 and click inside select2 element to se the new options available, they don’t populate while i’m typing my search

HTML:

<fieldset class="form-group position-relative has-icon-left maxlengthone" id="fieldset_profile_select">
<select class="max-length-one form-control form-group position-relative has-icon-left pl-4" multiple="multiple" id="profile_select">
</select>
<div class="form-control-position">
    <i class="fa fa-search"></i>
</div>
</fieldset>

Javascript:

$(document).ready(function () {
  let fieldset = document.getElementById('fieldset_profile_select')
  let inputSearch = fieldset.getElementsByTagName('input')[0]

  inputSearch.addEventListener('change', function(){
refreshProfileSelect(inputSearch.value)
  })

  function refreshProfileSelect(search) {
document.getElementById('profile_select').append('')
console.log('teste')
$.ajax({
  dataType: 'json',
  delay: 250,
  type: "GET",
  data: {
    'search': search,
    'sid': 2
  },
  url: '/getProfiles',
  success: function (response) {
    response.map(function(obj) {
      let option = document.createElement('option')
      option.value = obj.id
      option.innerHTML = `${obj.first_name} ${obj.last_name}`
      document.getElementById('profile_select').append(option)
    })
  }
});
  }
})

Is there a reason why you aren’t using the built-in AJAX capability of the Select2 widget? That might make it easier to do what you want.

In any case, I think the reason you don’t see your updates is that you must trigger the “change.select2” event after you update the <option>s in your <select> element to notify the Select2 widget that the underlying <select>'s data has been updated. See https://select2.org/programmatic-control/add-select-clear-items#creating-new-options-in-the-dropdown for details.

1 Like

Sorry, solved it by using the built-in ajax. I’m doing a dumb code on my first attempt.

No need to apologize. There are some really good use cases for fetching the data outside of Select2’s AJAX capability (for example if you don’t want/need the server-side search requirement).

In any case, I’m glad you were able to solve the issue.