jquery autocomplete with ajax source does not retrieve results - javascript

I have the following autocomplete that pulls from my ajax data source:
$("#id_q").autocomplete({
source: function (request, response) {
$.ajax({
url: "/search/autocomplete/",
dataType: "jsonp",
data: {
q: request.term
},
success: function (data) {
alert(data);
response(data);
}
});
},
minLength: 3,
select: function (event, ui) {
log(ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function () {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
Server side I can see that results are being returned correctly and look like:
{"results": ["BEEF", "BEEFARONI", "BEEFARONI", "BEEF", "BEET"]}
The success method never fires the alert.
Also should I rename request.term?
What am I doing wrong and where can I print the data I am returning to figure out what is going on?

Do you pass data to source method?
Is your url correct? I think yours is wrong, try writing the whole URL or use a REST client to check it.

Thanks for the hint #Andrew Whitaker . I removed the entire dataType line and it worked.

Related

jQuery autocomplete AJAX call doesn't work on 2nd match on select event

I am using autocomplete j query to suggest my users some questions and then when user select one of the questions it should shows the answer.
it works fine for the first click
when user clicks on each of these questions the answer is showing correctly but the problem is when user clear the inputs and write another word and then select one of the suggestion for the next time nothing happened after select each one
here is my jquery codes
$("#tags").autocomplete({
source: function (request, response) {
$.ajax({
dataType: 'json',
method: 'POST',
data: {
q: request.term
},
url: 'Help_And_Customer_Support/AjaxQuestion/q',
success: function (data) {
console.log(data.Qu);
response($.map(data, function (item) {
console.log(item.Ans);
return { label: item.Qu, id: item.Ans };
}))
},
});
},
select: function (event, ui) {
$("#showansw").css("height", 200);
var qans = ui.item.id;
var qq = ui.item.label;
$("#showansw p").html(qans);
$("#showansw h5").html(qq);
}
});
Appreciate any help. thanks

When using autocomplete, Is it possible to post above two data?

javascript
<script type="text/javascript">
function getCustomer() {
$('#CST_Idx_BI').autocomplete({
source: function (request, response) {
$.ajax({
type: 'POST',
url: '#Url.Action("JsonGetCustomerName","Customer")',
dataType: 'JSON',
data: { Keyword: $('#CST_Idx_BI').val(), CST_Idx: $('#CST_Idx_BI').val() },
success: function (data) {
response(
$.map(data, function (item, i) {
return {
label: item.CST_Name,
value: item.CST_Idx
}
})
);
}
});
},
focus: function (event, ui) {
event.preventDefault();
$(this).val(ui.item.question);
},
select: function (event, ui) {
$('#CST_Name_BI').val(ui.item.label);
},
})
}
</script>
When somebody inputs data(Regardless of whether numeric:CST_Inx or character:Keyword), I want to get the result they want.
But if somebody input data, Keyword = the data, CST_Idx = the data.
So I can't get any result... in my case, How can I solve this?
Is it possible to post above two data in same input element?
I mean, Regardless of whether CST_Inx or Keyword, when somebody inputs data in same input element, I want to get same result.
Umm, I've changed my post many times. In advance Sorry. I didn't check my error carefully bofore posting this. Sorry.

C# Webservice json data jquery ui with custom formatting

I'm using asp.net webservice to use it in jQuery UI autocomplete plugin and here is the data I'm getting.
{"d":[
{
"__type":"WebS.Model.SearchModel",
"MainCommodityId":1,
"MainCommodityName":"Pulses",
"SubcommodityId":3,
"SubCommodityName":"Urid Dal",
"BrandId":3,
"BrandName":"President"
},
{
"__type":"WebS.Model.SearchModel",
"MainCommodityId":1,
"MainCommodityName":"Pulses",
"SubcommodityId":1,
"SubCommodityName":"Red Gram",
"BrandId":4,
"BrandName":"President"
}
]
}
This is the script I'm using:
$(document).ready(function () {
$(".input-search").autocomplete({
source: function (request, response) {
$.ajax({
url: '/WebServices/GetAllBrandNames.asmx/getAllBrands',
data: "{ 'data': '" + request.term + "'}",
dataType: "json",
contentType: "application/json; charset=utf-8",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
value: item.BrandName,
label: item.SubCommodityName
}
}))
},
error: function (response) {
alert('error');
},
failure: function (response) {
alert('faii');
}
});
},
select: function (e, i) {
console.log(i.MainCommodityId);
console.log(i.SubcommodityId);
console.log(i.BrandId);
},
minLength: 1
}).autocomplete("instance")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + "" + item.BrandName + " in " + item.MainCommodityName + " - " + item.SubCommodityName + "</a>")
.appendTo(ul);
};
});
The issues are:
When I tried to enter keyword say: pre the aforesaid output is coming in json. However, the list is returning only one "President" item where it should display 2 items.
The list is displaying "undefined in undefined - undefined" instead of values after adding .autocomplete("instance")._renderItem function.
console.logs are also undefined after selecting an item.
How can these issues fixed?
The default behavior of the select event is to update the input with ui.item.value. This code runs after your event handler.
Simply prevent the default action on select and focus using event.preventDefault() or by return false and use _renderItem for custom dropdown.
focus: function(event, ui) {
// prevent autocomplete from updating the textbox
event.preventDefault(); // or return false;
}
select: function(event, ui) {
// prevent autocomplete from updating the textbox
event.preventDefault();
//do something
}
References:
jQuery UI Autocomplete Examples
Example 2
Finally, I was able to achieve what I wanted. Answering my question as it may helpful to someone.
javascript:
$(document).ready(function () {
$(".input-search").autocomplete({
source: function (request, response) {
$.ajax({
url: '/WebServices/GetAllBrandNames.asmx/getAllBrands',
data: "{ 'data': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
// don't forget to $.map to (data.d where d is the top node
return {
// assign values from json response for further use
brandid: item.BrandId,
brand: item.BrandName,
maincommodityid: item.MainCommodityId,
maincommodity: item.MainCommodityName,
subcommodityid: item.SubcommodityId,
subcommodity: item.SubCommodityName
}
}));
},
error: function (response) {
alert('Server Error. Please try again.');
},
failure: function (response) {
alert('Failed to get result');
}
});
},
focus: function (event, ui) {
// prevent autocomplete from updating the textbox
event.preventDefault();
},
select: function (event, ui) {
// prevent autocomplete from updating the textbox
event.preventDefault();
// do further action here such as assigning id to hidden field etc.
$(".input-search").val(ui.item.brand);
// navigate to the selected item's url ex: /catalogue/1/1/pulses/red-gram/4/president
var str = "/catalogue/" + ui.item.maincommodityid + "/" +
ui.item.subcommodityid + "/" + $.trim(ui.item.maincommodity.replace(/\s+/g, '-').toLowerCase()) + "/" +
$.trim(ui.item.subcommodity.replace(/\s+/g, '-').toLowerCase()) + "/" + ui.item.brandid + "/" +
$.trim(ui.item.brand.replace(/\s+/g, '-').toLowerCase());
window.location = str;
},
minLength: 3
}).autocomplete("instance")._renderItem = function (ul, item) {
// get values and create custom display
var $a = $("<a></a>");
$("<strong></strong>").text(item.brand).appendTo($a);
$("<span></span>").text(" in ").appendTo($a);
$("<span></span>").text(item.subcommodity).appendTo($a);
return $("<li></li>").append($a).appendTo(ul);
};
});
CSS:
ul.ui-front {
z-index: 1200; // change z-index according to your UI.
}
Usually I do this way and Its work.
$(document).ready(function () {
var jsondata=array();
$.post("/WebServices/GetAllBrandNames.asmx/getAllBrands",{data: request.term},function(data){
var data=JSON.parse(data);
$.each(data.d, function( index, value ) {
jsondata[index].value=value;
});
$(".input-search").autocomplete({
source:jsondata,
//other property and events
})
});
I mean apply source JSON after completing request because sometimes if AJAX takes some time to load execution pointer still execute rest of code without waiting for response.
I did not test this code but I always do this way and never get your kind of error. Good Luck

Displaying using JQuery UI Autocomplete not displaying results

I'm using Jquery UI's autocomplete, and I can see the proper JSON data coming back in Firebug. However, nothing's coming back to the textbox.
My JavaScript:
$(function() {
function log( message ) {
$( "<div/>" ).text( message ).prependTo( "#log" );
}
$("#tags").autocomplete({
source: function(request, response){
$.ajax ({
url: "/projectlist",
dataType: "json",
data: {style: "full", maxRows: 12, term: request.term}
});
}
})
});
You can see that from the snippet JSON data is being returned. But nothing is being displayed in the results table. Which should look like the the JQuery autocomplete example JQuery Autocomplete
Noyhing is displayed because you return nothing i think: you must add e success function to your ajax call (i added an example of a success response, if you tell us how your json is tructured i could help you better. in any case you must return an array of objects, and each object should have a property named 'label' and one named 'value':
$("#tags").autocomplete({
source: function(request, response) {
$.ajax({
url: "/projectlist",
dataType: "json",
data: {
style: "full",
maxRows: 12,
term: request.term
},
success: function(data) {
var results = [];
$.each(data, function(i, item) {
var itemToAdd = {
value: item,
label: item
};
results.push(itemToAdd);
});
return response(results);
}
});
}
});
I set up a fiddle here: http://jsfiddle.net/nicolapeluchetti/pRzTy/ (imagine that 'data' is the json that is returned)

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