Only started today but I'm having massive problems trying to understand JSON/AJAX etc, I've gotten my code this far but am stumped on how to return the data being pulled by the AJAX request to the jQuery Auto complete function.
var autocomplete = new function() {
this.init = function() {
$('#insurance_destination').autocomplete({
source: lookup
});
}
function lookup() {
$.ajax({
url: "scripts/php/autocomplete.php",
data: {
query: this.term
},
dataType: "json",
cache: false,
success: function(data) {
for (key in data) {
return {
label: key,
value: data[key][0]
}
}
}
});
}
}
And example of the JSON string being returned by a PHP script
{
"Uganda": ["UGA", "UK4", "Worldwide excluding USA, Canada and the Carribbean"]
}
Normally, you don't have to do ajax query yourself:
$('#insurance_destination').autocomplete('url_here', {options_here});
That's assuming we're talking about standard jquery autocomplete plugin. Do I understand you correctly?
edit
Check api
http://docs.jquery.com/Plugins/Autocomplete/autocomplete#url_or_dataoptions
There are also some examples.
This is the code I've ended up with, it works in Chrome and Firefox but not in IE 6/7...
var autocomplete = new function (){
this.init = function() {
$('#insurance_destination').autocomplete({
source: function(request, response) {
debugger;
$.ajax({
url: "scripts/php/autocomplete.php",
dataType: "json",
data: {query:this.term},
success: function(data) {
response($.map(data.countries, function(item) {
return {
label: '<strong>'+item.name+'</strong>'+' '+item.description,
value: item.name,
code : item.region
}
}))
}
})
},
minLength: 2,
select: function(event, ui) {
$('#insurance_iso_code_hidden').val(ui.item.code);
},
open: function() {
},
close: function() {
}
});
}
}
Related
I have a new project and decided to go with c# .net 6 MVC in VS2022...
In may old projects this code works flawless.
#section Scripts
{
<script type="text/javascript">
$("#Klijent_Name").autocomplete({
source: function (request, response) {
$.ajax({
url: "#Url.Action("SearchKlijenti")",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.label, value: item.label, id: item.id };
}))
}
})
},
minLength: 1,
select: function (event, ui) {
$("#KlijentId").val(ui.item.id);
$("#KlijentLabel").html(ui.item.label);
$("#SearchKupac").val("");
return false;
}
});
</script>
}
and latest variation of controller endpoint:
public JsonResult SearchKlijenti(string term)
{
var klijentVM = _klijent.Search(term);
if (klijentVM != null)
{
var items = klijentVM.Select(x => new { id = x.KlijentId, label = x.FriendlyName });
return new JsonResult(Ok(items));
}
return new JsonResult(Ok());
}
Using latest jQuery 3.6.1, and bootstrap 5.2.0. Tried using jquery-ui.js, jquery.unobtrusive-ajax.js...
Problem is that the call is not triggered, or not finding it's way to controller action. Have tried putting alert(); and omitting data manipulation and calls, but still nothing. When testing jQuery:
$("SearchKupac").keyup(function() {
alert();
});
works.
Tried to debug using Firefox, but either I don't know to use it, or the call is not triggered.
I don't know where and what to look anymore...
EDIT: Here is also HTML snippet
<label asp-for="Klijent.Name">Ime</label>
<input class="form-control ajax" asp-for="Klijent.Name" />
<span asp-validation-for="Klijent.Name" class="text-danger"></span>
I also tried selecting with $("input.ajax")... Tried double and single quotes. Bare in mind, this is a working code from MVC 5 project. It doesn't work in new project
If you want to use keyup event,here is a demo:
<input id="SearchKupac" />
js:
$("#SearchKupac").keyup(function() {
alert();
});
If the id of input is SearchKupac,you need to use $("#SearchKupac") in js.Also,you can use $("#SearchKupac") with autocomplete.
#section Scripts
{
<script type="text/javascript">
$("#SearchKupac").autocomplete({
source: function (request, response) {
$.ajax({
url: "#Url.Action("SearchKlijenti")",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.label, value: item.label, id: item.id };
}))
}
})
},
minLength: 1,
select: function (event, ui) {
$("#KlijentId").val(ui.item.id);
$("#KlijentLabel").html(ui.item.label);
$("#SearchKupac").val("");
return false;
}
});
</script>
}
So Firefox developer tool was of no help. Crome developer tool find an error. It was not apparent immediately, but the jquery-ui.js (of version 1.13.2 in my case) resolved the issue.
<script src="~/js/jquery-ui-1.13.2/jquery-ui.min.js"></script>
There was also an issue in controller. it has to be of type JsonResult and return Json(items) not Json(Ok(items))
public JsonResult SearchKlijenti(string term)
{
var klijentVM = _klijent.Search(term);
if (klijentVM != null)
{
var items = klijentVM.Select(x => new
{
id = x.KlijentId,
name = string.IsNullOrEmpty(x.Name) ? " " : x.Name,
friendly = string.IsNullOrEmpty(x.FriendlyName) ? " " : x.FriendlyName,
person = string.IsNullOrEmpty(x.PersonName) ? " " : x.PersonName,
tel = string.IsNullOrEmpty(x.Contact) ? " " : x.Contact,
mail = string.IsNullOrEmpty(x.Mail) ? " " : x.Mail,
oib = string.IsNullOrEmpty(x.OIB) ? " " : x.OIB,
adresa = string.IsNullOrEmpty(x.Adress) ? " " : x.Adress,
});
return Json(items);
}
return Json(null);
}
And for completeness, here is my script:
#section Scripts
{
<script type="text/javascript">
$("input.ajax").autocomplete({
source: function (request, response) {
$.ajax({
url: "#Url.Action("SearchKlijenti")",
type: "GET",
dataType: "json",
data: { term: request.term, maxResults: 10 },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.friendly,
value: item.friendly,
id: item.id,
name: item.name,
friendly: item.friendly,
person: item.person,
tel: item.tel,
mail: item.mail,
oib: item.oib,
adresa: item.adresa
};
}))
}
})
},
minLength: 1,
select: function (event, ui) {
$("#Klijent_KlijentId").val(ui.item.id);
$("#Klijent_KlijentName").val(ui.item.name)
$("#Klijent_FriendlyName").val(ui.item.label)
$("#Klijent_OIB").val(ui.item.oib)
$("#Klijent_PersonName").val(ui.item.person)
$("#Klijent_Contact").val(ui.item.tel)
$("#Klijent_Mail").val(ui.item.mail)
$("#Klijent_Adress").val(ui.item.adresa)
return false;
}
})
</script>
}
Did not yet test return Json(null), but that is not part of this exercise :)
I have an MVC - C# app with jquery autocomplete feature for some text boxes. Each View has autocomplete code, some are for the same field (different views), and some different fields as well.
ex.
Invoice\Create View customer text box
Payment\Create View customer text box
Payment\Create View Invoice Number text box
having autocomplete feature. All working as expected.
Here is a sample code (which is in each view for each control - this is for Customer)
$(document).ready(function () {
$("#CustomerName").autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("GetCustomers", "Invoices")',
datatype: "json",
data: {
term: request.term
},
success: function (data) {
response($.map(data, function (val, item) {
return {
label: val.CustomerName,
value: val.CustomerName,
CustomerId: val.CustomerId
}
}))
}
})
},
select: function (event, ui) {
$("#CustomerId").val(ui.item.CustomerId);
}
});
});
Now what I want is, create a common function in a file in Scripts Folder and call that, along with parameters, whenever I need this autocomplete feature to any control in any view.Is there a way to achieve it?
I tried the $(document).ready function in the view's script section, and few other options, but was unsuccessful.
Please let me know, at least whether this could be done or not
function (elementId,controllerName,actionName,fieldName) {
$("#"+elementId+"").autocomplete({
source: function (request, response) {
$.ajax({
url: 'api/'+controllerName+'/'+actionName+'',
datatype: "json",
data: {
term: request.term
},
success: function (data) {
response($.map(data, function (val, item) {
return {
label: val[0],
value: val[1],
fieldName: val.fieldId
}
}))
}
})
},
select: function (event, ui) {
$("#"+elementId+"").val(ui.item.fieldName);
}
});
}
I am passing complex JSON data to jQuery autocomplete plugin. And it is working fine so it shows the list of Products.
Now I want to get somehow Price that is already included into JSON data and when I select product from autocomlete list I would like to populate input tag with Price.
I really cannot get if it is possible to do. What I know that data is already in JSON but how to get it?
Any clue?
Here is JS for jQuery autocomplete plugin
function CreateAutocomplete() {
var inputsToProcess = $('[data-autocomplete]').each(function (index, element) {
var requestUrl = $(element).attr('data-action');
$(element).autocomplete({
minLength: 1,
source: function (request, response) {
$.ajax({
url: requestUrl,
dataType: "json",
data: { query: request.term },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Name,
value: item.Name,
realValue: item.UID
};
}));
},
});
},
select: function (event, ui) {
var hiddenFieldName = $(this).attr('data-value-name');
$('#' + hiddenFieldName).val(ui.item.UID);
}
});
});
}
To make clear item.LastPrice has Price data.
And HTML
#Html.AutocompleteFor(x => x.ProductUID, Url.Action("AutocompleteProducts", "Requisition"), true, "Start typing Product name...", Model.Product.Name)
In your ui.item object you should be able to find the the Price property in there and then set the value in the select function.
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Name,
value: item.Name,
realValue: item.UID,
price: item.LastPrice // you might need to return the LastPrice here if it's not available in the ui object in the select function
};
}));
},
..
select: function (event, ui) {
var hiddenFieldName = $(this).attr('data-value-name'),
unitPriceEl = $('#price');
$('#' + hiddenFieldName).val(ui.item.UID);
unitPriceEl.val(ui.item.LastPrice); //set the price here
}
Thanks to dcodesmith!!! I am gonna mark his solution like an answer but just in case I will share my final code that is working fine now.
function CreateAutocomplete() {
var inputsToProcess = $('[data-autocomplete]').each(function (index, element) {
var requestUrl = $(element).attr('data-action');
$(element).autocomplete({
minLength: 1,
source: function (request, response) {
$.ajax({
url: requestUrl,
dataType: "json",
data: { query: request.term },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Name,
value: item.Name,
realValue: item.UID,
lastPrice: item.LastPrice
};
}));
},
});
},
select: function (event, ui) {
var hiddenFieldName = $(this).attr('data-value-name');
$('#' + hiddenFieldName).val(ui.item.UID);
var unitPriceEl = $('#UnitPrice');
unitPriceEl.val(ui.item.lastPrice);
console.log(ui.item.lastPrice);
}
});
});
}
I am trying to fetch the values as Autocomplete jQuery method and store the selected input values into a text box (push to text box). Sounds easy but this JSON schema is kinda taking buzzy time.
Can I get a quick help here?
http://jsfiddle.net/ebPCq/1/
jQuery Code:
$("#material_number").autocomplete({
source: function (request, response) {
$.ajax({
url: "http://ws.geonames.org/searchJSON",
dataType: "json",
data: {
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function (data) {
response($.map(data.geonames, function (item) {
return {
// following property gets displayed in drop down
label: item.name + ", " + item.countryName,
// following property gets entered in the textbox
value: item.name,
// following property is added for our own use
my_description: item.fcodeName
}
}));
}
});
After fixing up and finalizing the initial functionality, I came upon conclusion with this fiddle as the solution to my query posted above.
http://jsfiddle.net/ebPCq/7/
JS Code:
$(function () {
$("#input").autocomplete({
source: function (request, response) {
$.ajax({
url: "http://ws.geonames.org/searchJSON",
dataType: "json",
data: {
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function (data) {
response($.map(data.geonames, function (item) {
return {
// following property gets displayed in drop down
label: item.name + ", " + item.countryName,
// following property gets entered in the textbox
value: item.name,
// following property is added for our own use
my_description: item.fcodeName
}
}));
}
});
},
minLength: 2,
select: function (event, ui) {
if (ui.item) {
$("#push-input").prepend(ui.item.value + '\r\n');
}
}
});
});
I'm sorry similar post is already there in the community, But i'm finding it strange. Its working fine but it affected my other views and not allowing other view pages to populate any dialogue boxes..
I tried to fix it by wrapping it in function() like this
$('#_auto').autocomplete(function(){
But, with this i'm not getting jason values in the _auto textfield and getting unexpected token error with following line.
can anyone help me to solve this please.
source: function(request,response){
this is my code:
$(function () {
$('#_auto').autocomplete({
selectFist: true,
minLength: 2,
source: function (request, response) {
var sval = $('#_auto').val();
//alert(sval);
$.ajax({
url: BASE_URL + '/controller/search/',
type: 'POST',
data: {
'term': sval,
},
dataType: 'json',
success: function (data) {
console.log(data);
var dta = [];
orgdetails = [];
//response(data.d);
for (var i in data) {
dta.push(data[i].name);
orgdetails[data[i].name] = data[i].id;
}
response(dta); //response(dta);
},
error: function (result) {}
}); //ajax
}
}).focus(function () {
$(this).trigger('keydown.autocomplete');
});
});
Many Thanks
I think the for loop should be
var dta = $.map(data, function(v, i){
orgdetails[v.name] = v.id;
return {
label: v.name,
id: v.name
};
});
Fiddle.
Another observation, You can get the current searched term using request.term rather than $('#_auto').val()
Complete code:
$('#_auto').autocomplete({
selectFist: true,
minLength: 2,
source: function (request, response) {
$.ajax({
url: BASE_URL + '/controller/search/',
type: 'POST',
data: {
'term': request.term,
},
dataType: 'json',
success: function (data) {
console.log(data);
orgdetails = {};
var dta = $.map(data, function(v, i){
orgdetails[v.name] = v.id;
return {
label: v.name,
id: v.name
};
});
response(dta); //response(dta);
},
error: function (result) {}
}); //ajax
}
}).focus(function () {
$(this).trigger('keydown.autocomplete');
});