I have a form where the country states have to be displayed in a dropdown, since there was autocomplete already added, I'm getting the response as array in "console.log(data)" but only when I search a state, however I'm unable to change the autocomplete to selection list, I did attempt by changing jquery autocomplete to use select2,selectmenu or on change, but this only works with autocomplete. I do not require the autocomplete search at all but just the dropdown with the country states to be listed from data. below is the code where I'm using a ajax post to get the response using a api call from php file. how do I get the list of country states in selection list and trigger an event when selected, I'm a newbie in this domain.
Some of the sources that I followed,
jQuery autocomplete + ajax API call only triggers list on spacebar/down arrow?
jQuery Autocomplete, passing success data to the select method
html -
<select id = "country_state"></select>
jquery -
('#country_state').autocomplete({
source: function(request, response) {
Request.AbortAll();
$.ajax({
type: "POST",
minLength: 3,
url: base_path + "countrystatelist.php",
dataType: "json",
data: {
q: request.term
},
beforeSend: function (jqXHR, settings) {
Request.List.push(jqXHR);
},
success: function(data) {
response(data);
console.log(data);
}
});
},
select: function(event, ui) {
$('#country_state').attr('country_state-id', ui.item.id);
}
});
- php -
public function AllState() {
$results = [];
$Country_states_info = CountryState::GetAllStates(); /* from api */
foreach ($Country_states_info as $country_state) {
if (!isset($country_state['name'])) {
continue;
}
$results[] = [
'value' => $country_state_name,
'label' => $country_state_name,
'id' => $country_state['id'],
];
}
return new JsonResponse($results);
}
using select2
jQuery('#country_state').select2({
source: function(request, response) {
Request.AbortAll();
jQuery.ajax({
type: "POST",
minLength: 3,
url: base_path + "countrylist.php",
dataType: "json",
data: {
q: request.term
},
beforeSend: function (jqXHR, settings) {
Request.List.push(jqXHR);
},
success: function(data) {
// response(data);
return {
results: data.items
};
console.log(data);
}
});
},
select: function(event, ui) {
$('#country_state').attr('country_state-id', ui.item.id);
}
});