Changing autocomplete function to display as dropdown list - php

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);
}
});

Would suggest the following updates to your 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;
}
array_push($results, [
'value' => $country_state['name'],
'label' => $country_state['name'],
'id' => $country_state['id'],
]);
}
return new JsonResponse($results);
}
I did not see where $country_state_name was defined. I suspect you meant $country_state['name'].

Related

Problem with json data source on ui autocomplete

I have a problem with my code. I receive data via ajax and it works, but the problem is that when I try to search for an element and all the elements appear so the search does not work properly.
JS code :
let marque_id =$("#marque_id").val();
$( "#grp_name" ).autocomplete({
source: function( request, response ) {
$.ajax({
url:"abonne/ajax_get_grp_autorisation",
method:"POST",
dataType: "json",
data: {
marque_id : id_marque
},
success: function( data ) {
response( data );
console.log(data);
}
});
},
select: function (event, ui) {
// Set selection
$('#grp_name').val(ui.item.label); // display the selected text
$('#id_grp_selected').val(ui.item.id); // save selected id to input
return false;
}
});
PHP code :
$data = array();
while($line = mysqli_fetch_object($liste_grp) ){
$data[] = array("label"=>$line->grp_nom,"value"=>$line->grp_nom ,"id"=>$line->groupement_id);
}
echo json_encode($data);
result
you should send the text you are searching for to ajax request so your autocomplete function should be
let marque_id =$("#marque_id").val();
$( "#grp_name" ).autocomplete({
source: function( request, response ) {
$.ajax({
url:"abonne/ajax_get_grp_autorisation",
method:"POST",
dataType: "json",
data: {
marque_id : id_marque ,
term: request.term
},
success: function( data ) {
response( data );
console.log(data);
}
});
},
select: function (event, ui) {
// Set selection
$('#grp_name').val(ui.item.label); // display the selected text
$('#id_grp_selected').val(ui.item.id); // save selected id to input
return false;
}
});
request.term is your search text and in your example it is group text
and also you need to modify your mysql query and add condition (like)
for example
$rs = mysql_query("SELECT * FROM table WHERE colum LIKE '%" . $_POST['term'] . "%'");
and finally you can check https://jqueryui.com/autocomplete/#remote-jsonp
I would advise the following jQuery:
$( "#grp_name" ).autocomplete({
source: function(request, response) {
$.ajax({
url:"abonne/ajax_get_grp_autorisation",
method:"POST",
dataType: "json",
data: {
marque_id: request.term
},
success: function( data ) {
console.log(data);
response(data);
}
});
},
select: function (event, ui) {
// Set selection
$('#grp_name').val(ui.item.label); // display the selected text
$('#id_grp_selected').val(ui.item.id); // save selected id to input
return false;
}
});
This is a small change. This will send the request.term to your PHP Script. For example, if the user types "gro", this will be sent to your script and would be accessed via:
$_POST['marque_id']
This would assume your SQL Query is something like:
$stmt = $mysqli->prepare("SELECT * FROM table WHERE column LIKE '?%'");
$stmt->bind_param("s", $_POST['marque_id']);
$stmt->execute();
$liste_grp = $stmt->get_result();
$data = array();
while($line = $liste_grp->fetch_assoc()) {
$data[] = array(
"label" => $line['grp_nom'],
"value" => $line['grp_nom'],
"id" => $line['groupement_id']
);
}
$stmt->close();
header('Content-Type: application/json');
echo json_encode($data);
This uses the MySQLi Prepared Statement, and will help prevent SQL Injection. I also included the JSON Header as good practice. The result of search "gro" would be something like:
[
{
"label": "GROUPE DATAPNEU TEST",
"value": "GROUPE DATAPNEU TEST",
"id": 1
}
];
Thanks guys i found a solution it works better
i used tokeninput with many options
http://loopj.com/jquery-tokeni
$.ajax({
url:"ajax_get_societe_authorisation",
method:"POST",
scriptCharset: "iso-8859-1",
cache: false,
dataType: "json",
data: {
marque_id : id_marque
},
success: function( data ) {
console.log(data);
$("#soc_name").tokenInput(data
,{
tokenLimit: 1,
hintText: "Recherche une société par son nom",
noResultsText: "Aucune société trouvé",
searchingText: "Recherche en cours ...",
onAdd: function (data) {
$("#soc_id").val(data.id);
},
onDelete: function (item) {
$("#soc_id").val("");
}
}
);
}
});

Send search term and custom flag to php function via Ajax

I'm looking for a way to filter autocomplete results if the custom flag is sent to function, together with the search term. For example, if the user wants to find all cities that have stadium/swimming pool, etc. he can pick this as a filtering option.
var filter = $.inArray('1', selectedTypes);
This line searches only one flag to see if it's working
I have autocomplete set up and working fine without the filter, but now I'm not sure how to set it up. Any help is appreciated.
jQuery:
$('#city').autocomplete({
delay: 0,
source: function (request, response) {
var selectedTypes = $("#filter").val();
var filter = $.inArray('1', selectedTypes);
$.ajax({
url: "/cities/ajaxGetCities/" + request.term,
dataType: "json",
contentType: "application/json",
success: function (data) {
if (typeof(data[0]) === 'undefined') {
return null;
}
response($.map(data, function (value, key) {
return {
label: value.cityName,
value: value.id
}
}));
}
});
},
select: function (event, ui) {
$("#city").val(ui.item.label);
return false;
},
autoFocus: true
});
PHP (in controller, using CodeIgniter):
public function ajaxGetCities(string $term, int $filter = null)
{
if ($filter) {
$cities = getFilteredCities($filter)
} else {
$cities = getCities($term);
}
$filteredCities = [];
foreach ($cities as $city) {
if (stripos($city->cityName, $term) !== false ) {
$filteredCities[] = $city;
}
}
exit(json_encode($filteredCities));
}
I tried this in JS, and removed func arguments in controller but the $_POST was empty
$.ajax({
type: 'POST',
data: {term: request.term, flag: filter},
url: "/cities/ajaxGetCities",
dataType: "json",
contentType: "application/json",
success: function (data) {
if (typeof(data[0]) === 'undefined') {
return null;
}
response($.map(data, function (value, key) {
return {
label: value.cityName,
value: value.id
}
}));
"the $_POST was empty"
...this is because you send the data as JSON, due to specifying
contentType: "application/json"
in the AJAX options. But what is the server expecting? By default PHP expects normal form data, not JSON. If you send JSON, a little bit of extra code is needed to process it.
If you simply remove that line from your AJAX options, the data will be sent as form data (the default) and PHP should be able read it happily as standard POST variables.

How to disable click when autocomplete Field "no rseult found" via ajax call

I have done almost everything and I have successfully implemented autocomplete searching with ajax. Now problem is that when no data is found in autocomplete searching by default it shows No Result found. When I click on "NO Results Found" it is appearing on textbox. I want when No Results Found and user tries to click on that it should be no clickable
Here is My jquery Code:
src = "{{ route('searchajax') }}";
$("#search_text").autocomplete({
source: function(request, response) {
$.ajax({
url: src,
dataType: "json",
data: {
term : request.term
},
success: function(data) {
response(data);
}
});
},
min_length: 3,
});
And My laravel 5.2 function
public function autoComplete(Request $request) {
$query = $request->get('term','');
$states=DB::table('states')->where('state','LIKE','%'.$query.'%')->get();
$data=array();
foreach ($states as $state) {
$data[]=array('value'=>$state->state,'id'=>$state->id);
}
if(count($data))
return $data;
else
return ['value'=>'No Result Found','id'=>''];
}
This is the answer you are looking for
You can use the response function to check if you do have results. If not, just push "No results found" to your list and then use _renderItem to disable this option.
$("#search_text").autocomplete({
source: function(request, response) {
$.ajax({
url: src,
dataType: "json",
data: {
term : request.term
},
success: function(data) {
response(data);
}
});
},
min_length: 3,
response: function(event, ui) {
if( ui.content.length === 0 ) {
ui.content.push({
'label': 'No results found',
'value': ''
});
}
}).data("ui-autocomplete")._renderItem = function(ul, item) {
if( item.value == '' ) {
return $('<li class="ui-state-disabled">'+item.label+'</li>').appendTo(ul);
} else {
return $("<li>").append("<a>" + item.label + "</a>").appendTo(ul);
}
};
I made this fiddle so you can see it working.

Add some default options in select2 when dropdown is open in remote data

I am using Select2 with remote data. when i click on drop-down. no option will shows until write in search box.
But i want to show some data when drop-down open.
I am trying it with initselection or data but its initialize when data present in selected value.
$('.countrySelection').select2({
placeholder: "Select Country",
allowClear: true,
minimumInputLength: 1,
ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
url: base_url+'ajax_response/getCountry',
dataType: 'json',
quietMillis: 100,
data: function (term, page) {
return {
q: term, // search term
page: page
};
},
results: function (data, page) {
$(".statenoSelect").select2("val", "");
$(".citynoSelect").select2("val", "");
var more = (page * 2) < data.page
return {
results: data.items,
more: more
};
},
cache: true
},
initSelection: function(element, callback) {
var id = $(element).val();
if (id !== "") {
$.ajax(base_url+'ajax_response/getCountry?id=' + id, {
dataType: "json"
}).done(function(data) { callback(data['items'][0]); });
}else{
$.ajax(base_url+'ajax_response/getCountry?default=true', {
dataType: "json"
}).done(function(data) { callback(data['items']); });
}
},
data:function(element, callback) {
callback(JSON.parse($(element).attr('data-selection')));
},
formatResult: repoFormatResult,
formatSelection: repoFormatResult,
dropdownCssClass: "bigdrop",
escapeMarkup: function (m) { return m; }
}).focus(function () { $(this).select2('open'); });
Its working with ajax, but how can I add options without search anything

Passing an object to onSelect using Bootstrap3-typeahead

BootStrap3-TypeAhead
Hey all, I'm having trouble figuring out how I should be passing along an object of anything more than the default to onSelect for more extensive usage. Here's my code, any help would be greatly appreciated!
$("input[type='text']").typeahead({
onSelect: function(item) {
// Do things with the item object here.
},
items: 10,
ajax: {
url: "modules/scripts/Search.php",
timeout: 500,
triggerLength: 1,
method: "POST",
preDispatch: function (str) {
return {
String: str,
State: $("#"+$("#"+InputBox).attr("data-place")+"StateText").attr("data-sc")
}
},
preProcess: function (data) {
if (data.success === false) { return false; }
// I think I'd create the item object here, or pass it along?
var DD = [];
$.each(data, function(key, value) {
DD.push(value['City']+" - "+value['Zip']);
TempArr[value['ID']] = data[key];
});
return DD;
}
}
});
Seems you are using jQuery-UI autocomplete syntax. Typeahed use Bloodhound suggestion engine. Check Typeahead documentation.
Hearing Typeahead custom-event: typeaead:selected let ou retrieve the jQuery event object, the suggestion object, and the name of the dataset the suggestion belongs to.
I ended up solving this issue using the .remote.filter: function(obj) {} options. Here's a snip:
var AjaxOptions = {
type: "POST",
cache: false,
data: { limit: 10 },
beforeSend: function(jqXHR, settings){
// Manipulate settings.data to send more information than just the query string.
},
complete: function(data) {
// If desired, you could do a 'how long this query took' display here.
}
}
var InputArea = new Bloodhound({
datumTokenizer: function(d) { return Bloodhound.tokenizers.whitespace(d.val); },
queryTokenizer: Bloodhound.tokenizers.whitespace,
limit: 10,
remote: {
cache: false,
url: 'scripts/Query.php?q=%QUERY',
filter: function (InputArea) {
return $.map(InputArea, function (data) {
// Do whatever you want with 'data', then return it
return {
foo: bar,
arnold: data.palmer
};
});
},
ajax: AjaxOptions,
}
});

Categories