jquery autocomplete not showing result - javascript

I try to make autocomplete with jquery filter by id category, when I type the result not showing, like this picture :
When I click tab network I've got the data like this picture :
This is my code javascript :
<script type="text/javascript">
$(function() {
$(".keyword").autocomplete({
source: function(request, response) {
$.ajax({
url: "search/autocomplete",
type: "GET",
dataType: "json",
data: {'id':1},
success: function(data) {
response($.map(data, function(item) {
return {
label: item.name,
value: item.id
};
}));
}
});
},
select:function(event,ui) {
$(".keyword").val(ui.item.label);
return false;
},
minLength: 2,
}).bind('focus', function () {
$('.ui-autocomplete').css('z-index','9999').css('overflow-y','scroll').css('max-height','300px');
// $('.ui-autocomplete').css('background','#09121a').css('color','#fff');
// $('.ui-menu .ui-menu-item-wrapper').css('padding','11px 1em 3px 1.4em !important');
// $(this).autocomplete("search");
// var btncategory = $('.btn-category').width();
// var left = '-'+btncategory+'px';
});
});
</script>
If I type "a" - I don't see anything, but when I delete "a" - I see all three. So it's look like the jQuery doesn't know that it should look for a value in object.name.

As Tan Duong said, your response only contains the attribute called value. It is not able to find name and id, hence your results are showing blank data.
Change your success function to this:
success: function(data) {
response($.map(data, function(item) {
return {
label: item.value,
value: item.value
};
}));
}

Related

Select2 AJAX not showing "No data found" when no data in database, instead showing search parameter as option to select

I've been working on a project where I've to load select2 option from ajax call.
The code is working fine, except in search result, it always shows search parameter as option. Even if there is no data in database, it still showing it as option, not showing "No data found".
My code is here
$(".search_user").select2({
minimumInputLength: 11,
tags: [],
ajax: {
url: "/user/get_user",
dataType: 'json',
type: "GET",
quietMillis: 250,
data: function (term) {
return {
term: term
};
},
processResults: function (data) {
var Return = [];
for (var i in data.item) {
console.log(data.item[i])
if (data.item[i].id != data.item[i].text) {
Return.push(data.item[i]);
}
}
return {
results: Return
}
}
}
});
my return json is like this
{"item":[{"id":16,"name":"Razin Abid"}]}
My view is looking like this.
Please help me out.
If you using firemodal on stisla
$('#modal-create-promo').click(()=>{
setTimeout(()=>{
$('#fire-modal-1').removeAttr('tabindex');
});
});
$("#modal-create-promo").fireModal({
...
});
It's work for me
Thats because you enable tags option from select2. You need to remove 'Tags:[]' from your code.
visit : https://select2.org/tagging
so, your code should be like this:
$(".search_user").select2({
minimumInputLength: 11,
ajax: {
url: "/user/get_user",
dataType: 'json',
type: "GET",
quietMillis: 250,
data: function (term) {
return {
term: term
};
},
processResults: function (data) {
var Return = [];
for (var i in data.item) {
console.log(data.item[i])
if (data.item[i].id != data.item[i].text) {
Return.push(data.item[i]);
}
}
return {
results: Return
}
}
}
});

Change remote url based on search query

I have a select2 field which is retrieving data from a remote api. I can get that working. What I'm trying to do is change the remote url based on what the user has typed. If the first two letters typed are for example "AA" then search using a url and when the first two characters are "88" then search using another url.
This is my code so far:
this.selector.select2({
minimumInputLength: 2,
ajax: {
url: function(param){return 'http://localhost:3000/suggestions?&'},
dataType: 'json' ,
data: function (params) {
var query = {
search: params.term,
}
return query;
},
processResults: function(data) {
var results = [];
$.each(data, function (index, search) {
results.push({
id: search.id,
text: search.val
});
});
return {
"results":results
};
},
},
width: 'resolve',
});
I've looked but can't find an event which is fired when typing(searching).
According to docs the params argument passed to url callback is the same as in data callback. So you can rewrite your code as:
this.selector.select2({
minimumInputLength: 2,
ajax: {
url: function (params) {
var firstTwoLetters = params.term.slice(0, 2);
if (firstTwoLetters == '88') {
return 'some url';
} else if (firstTwoLetters == 'AA') {
return 'another url'
} else {
return 'http://localhost:3000/suggestions?&'
}
},
dataType: 'json',
data: function (params) {
var query = {
search: params.term,
}
return query;
},
processResults: function (data) {
var results = [];
$.each(data, function (index, search) {
results.push({
id: search.id,
text: search.val
});
});
return {
"results": results
};
},
},
width: 'resolve',
});
I hope I understood your last request correctly.
The oninput event occurs as you type.
note: I'd rather comment it and not use Answer, however, I have less than 50 rep.

Storing JSON result from ajax request to a javascript variable for Easyautocomplete

I'm trying to implement the EasyAutoComplete plugin on a field based on the value filled in another field, using ajax requests.
I have a customerid field and when it's value changes, I want the productname field to show all products related to that customerid using the EasyAutoComplete plugin.
Here is what I have so far:
$('#customerid').on('change',function() {
var products2 = {
url: function(phrase) {
return "database/FetchCustomerProducts.php";
},
ajaxSettings: {
dataType: "json",
method: "POST",
data: {
dataType: "json"
}
},
preparePostData: function(data) {
data.phrase = $("#customerid").val();
return data;
},
getValue: "name",
list: {
onSelectItemEvent: function() {
var value = $("#productname").getSelectedItemData().id;
$("#productid").val(value).trigger("change");
},
match: {
enabled: true
}
}
};
$("#productname").easyAutocomplete(products2);
});
Contents of FetchCustomerProducts.php:
if(!empty($_POST["customerid"])){
$products = $app['database']->Select('products', 'customerid', $_POST['customerid']);
echo json_encode(['data' => $products]);
}
However it's not working. The code is based on the 'Ajax POST' example found on this page.
you can using element select category add is class "check_catogory"
after using event click element select get value is option, continue send id to ajax and in file php, you can get $_POST['id'] or $_GET['id'], select find database,after echo json_encode
$("#customerid").change(function(){
var id = $(this).val();
if(id!=""){
$.ajax({
url:"database/FetchCustomerProducts.php",
type:"POST",
data:{id:id},
dataType: "json",
cache:false,
success:function(result){
var options = {
data:result,
getValue: "name",
list: {
onSelectItemEvent: function() {
var value = $("#productname").getSelectedItemData().id;
$("#productid").val(value).trigger("change");
},
match: {
enabled: true
}
}
};
$("#productname").easyAutocomplete(options);
}
})
}
});

jquery ui autocomplete displays only first item in db

Am using JQuery Autocomplete on my templete, but as i get the results the Autocomplete only displays one item despite that the results that are fetched have more that one item. It only shows the first item on the list!
Example:
if i have a result list with ('type1', 'type2', 'type3')
and on the autocomplete i type 't' it only displays type1 on the drop down!
I am a newbie in jquery kindly rectify my mistakes( if any)
My autocomplete code:
$(".fro").each(function() {
$(this).autocomplete({
source : function(request, response) {
$.ajax({
serviceUrl: '${pageContext.request.contextPath}/index.htm',
datatype: "json",
paramName: "fro",
delimiter: ",",
data : {
term : request.term
},
success : function(data) {
response($.map(data.result, function(item) {
$.each(data, function() {
return {
label : this.fro,
value : this.fro
}
});
}));
}
});
},
minLength:1
});
});
My response controller looks like this:
#RequestMapping(value = "/getTags.htm", method = RequestMethod.GET, headers="Accept=*/*")
public #ResponseBody List<SearchFiller> getTags(#RequestParam("fro") String fro) {
return simulateSearchResult(fro);
}
private List<SearchFiller> simulateSearchResult(String fro) {
List<SearchFiller> data=searchFlightDao.fillerList();
List<SearchFiller> result = new ArrayList<SearchFiller>();
for (SearchFiller tag : data) {
if (tag.getFro().contains(fro)) {
result.add(tag);
}
}
return result;
}
Right answer gets appreciated
Let you try this:
$(".fro").each(function() {
$(this).autocomplete({
source : function(request, response) {
$.ajax({
serviceUrl: '${pageContext.request.contextPath}/index.htm',
datatype: "json",
paramName: "fro",
delimiter: ",",
data : {
term : request.term
},
success : function(data) {
dataArray = new Array();
$.each(data, function() {
var t = { label : this.fro, value : this.fro };
dataArray.push(t);
});
response(dataArray);
}
});
},
minLength:1
});
});

jQuery autocomplete - pass targeted element attribute as an extra parameter?

I'm using the jQuery UI Autocomplete plug-in to make an ajax call and retrieve data. As well as passing the text of the input element I'm trying to pass in the 'id' attribute of the input element as an additional parameter. An extract of my code looks like this -
$("#autocomplete input").autocomplete({
source: function(request, response) {
$.ajax({
url: "search.php",
dataType: "json",
data: {
term: extractLast(request.term),
extra_param: $(this).attr('id')
},
success: function(data) {
response($.map(data, function(item) {
return {
label: item.label,
value: item.name
}
}))
}
})
},
});
The extra parameter is added to the 'data' property in the ajax call. It works okay if I specifically pass in a value e.g. '3' but I want to pass the 'id' attribute of the input element the function is being called on e.g. $(this).attr('id').
I assume it's a problem with 'this' not being evaluated in this part of the code, but I'm at a loss to see how else I can reference the element that is being targeted. Any help appreciated!
$('#autocomplete input').each(e, function() {
$(e).autocomplete('/path?param=' + $(e).attr('id'), function() { ... });
});
$('#autocomplete input').each(e, function() {
$(e).autocomplete({ source:function ... extra_param: $(e).attr('id') ... });
});
There maybe a more elegant way, but, I know autocomplete is somewhat sophisticated. I personally generate the request w/get parameters and use formatItem/formatResult instead of assigning the source to an ajax call.
I've got it working by breaking the autocomplete call out into an each. This allows me to capture the target element before I execute the autocomplete -
$("#autocomplete input").each(function() {
var that = this;
$(that).autocomplete({
source: function(request, response, this_element) {
$.ajax({
url: "search.php",
dataType: "json",
data: {
term: extractLast(request.term),
extra_param: $(that).attr('id')
}
....
"Source" is the ID of your input, you receive this item and save it in the variable, "that". When the input "Source" calls the autocomplete function, you can send the value of your id stored in the variable "that" for AJAX.
Example:
<script type="text/javascript">
$(document).ready(function() {
$("#Source").each(function() {
var that = this;
var url = "<?php echo constant('URL'); ?>";
$(that).autocomplete({
source: function(request, response){
$.ajax({
url: url+"models/queries/C_getOptions.php",
dataType:"json",
data:{
word:request.term,
id : $(that).attr('id')
},
success: function(data){
response(data);
}
});
},
minLength: 1,
select: function(event,ui){
//alert("Selecciono: "+ ui.item.label);
}
});
})
});

Categories

Resources