ajax auto-completion bind data to textbox - javascript

Am getting data from ajax call, How to bind data for text box auto-completion with name and id as fields.
How to bind the data in front end and get selected name's id in back end java.
$(document).ready(function() {
$(function() {
$("#customerName").autocomplete({
source : function(request, response) {
$.ajax({
url : "/customer/getByNames",
type : "GET",
data : {
name : $("#customerName").val()
},
dataType : "json",
success : function(data) {
response(data);
}
});
}
});
});
});
<input type="text" id="customerName" name="customerName"
th:field="*{customer.name}" />
JSON returned data from ajax call (Data at sucess)
[
{"id": 1,"name": "Customer_01"},
{"id": 2,"name": "Customer_02"},
{"id": 3,"name": "Customer_03"},
{"id": 4,"name": "Customer_04"}
]
Need to bind name field of JSON to textbox as auto-completion
Can any one help me?

You can pass the data from your AJAX call to a method to initialize the auto complete plugin.
The method can have a name of selectors to initialize or if your selectors are in the data then you can map the data to an array of selectors you want to bind auto complete for.
$(document).ready(function()
$.ajax({
url : "/customer/getByNames",
type : "GET",
data : {
name : $("#customerName").val()
},
dataType : "json",
success : function(data) {
setAutoComplete(data);
}
});
});
function setAutoComplete(data)
{
var selectors = ["#someId", "someotherId"];
//if your selector are in the data then use data.map to get your selectors.
selectors.forEach(function(selector)
{
$(selector).autocomplete({
source: data
});
}
}
If your data has a special format you can use a custom render function to initialize the auto complete plugin.
For example, this allow you to group auto complete data with a category and field into groups using this JSON set as formModel:
{
"Contact":{
"FirstName":"Contact.FirstName",
"MiddleInitial":"Contact.MiddleInitial",
"LastName":"Contact.LastName",
"Address1":"Contact.Address1",
"Address2":"Contact.Address2",
"City":"Contact.City",
"State":"Contact.State",
"PostalCode":"Contact.PostalCode",
"WorkPhone":"Contact.WorkPhone",
"HomePhone":"Contact.HomePhone",
"Email":"Contact.Email"
},
"UDFs":{
"ModifiedBy":"Contact.UDFs.ModifiedBy",
"ModifiedDate":"Contact.UDFs.ModifiedDate",
"SessionId":"Contact.UDFs.SessionId",
"FormData":"Contact.UDFs.FormData"
}
}
I use this code:
function getFormModel() {
var availableTags = [];
for (var category in formModel) {
var fields = formModel[category];
for (var field in fields) {
availableTags.push({
category: category,
label: field,
value: fields[field] });
}
}
return availableTags;
}
function setAutoComplete(el) {
$(el).autocomplete({
source: getFormModel(),
create: function () {
//access to jQuery Autocomplete widget differs depending
//on some jQuery UI versions - you can also try .data('autocomplete')
$(this).data('uiAutocomplete')._renderMenu = customRenderMenu;
}
});
}
var customRenderMenu = function (ul, items) {
var self = this;
var categoryArr = [];
function contain(item, array) {
var contains = false;
$.each(array, function (index, value) {
if (item == value) {
contains = true;
return false;
}
});
return contains;
}
$.each(items, function (index, item) {
if (!contain(item.category, categoryArr)) {
categoryArr.push(item.category);
}
console.log(categoryArr);
});
$.each(categoryArr, function (index, category) {
ul.append("<li class='ui-autocomplete-group'>" + category + "</li>");
$.each(items, function (index, item) {
if (item.category == category) {
self._renderItemData(ul, item);
}
});
});
};

Final working code :
$(document).ready(function() {
$(function() {
$("#customerName").autocomplete({
source : function(request, response) {
$.ajax({
url : "/customer/getByNames",
type : "GET",
data : {
name : $("#customerName").val()
},
dataType : "json",
success : function(data) {
$("#customerName").autocomplete({
source : data
});
},
appendTo: "#customerNameResult"
});
}
});
});
});

Related

Attach AJAX fetched value with Select2

I am trying to attach AJAX fetched value with Select2. My JavaScript code is like below.
(function($) {
$(document).ready(function() {
$(".volunteer").on("click", function (event) {
let element_id = event.target.id;
// Check if select is already loaded
if (!$(this).has("select").length) {
var cellEle = $(this);
// Populate select element
cellEle.html(`<select class="js-example-basic-multiple" multiple="multiple"></select>`);
// Initialise select2
let selectEle = cellEle.children("select").select2({
ajax: {
url: "/wordpressbosta/matt/wp-admin/admin-ajax.php",
dataType: 'json',
data: function (params) {
return {
q: element_id,
action: 'get_data'
};
},
type: "post",
processResults: function(data) {
var options = [];
if ( data ) {
$.each( data, function( index, text ) {
options.push( { text: text } );
});
}
return {
results: options
};
}
}
});
}
});
});
})(jQuery)
I am getting output like below.
If I click on any value, it is not set to the select box. Values are not working.
Select2 requires that each option has an id property and a text property. In the code above the processResults method is returning an array of objects which contain only a text property, without an id. When adding objects to the array in processResults an id should be included:
options.push({ id: id, text: text });
Details on this format can be found at https://select2.org/data-sources/formats. As per this page:
Blank ids or an id with a value of 0 are not permitted.
You could either use text as the id value if it's unique, or use index + 1 (+ 1 to avoid a value of 0). In the below example code text is used.
processResults: function(data) {
var options = [];
if (data) {
$.each(data, function (index, text) {
options.push({ id: text, text: text });
});
}
return {
results: options
};
}

How to store JSON data in an element using jquery

My page is receiving JSON encoded data from a php script. Using my browsers dev network tool I can see the data is as follows:
{"state":200,"message":null,"result":"..\/0images\/listimg\/orig\/54ab4719bf848.jpeg","id":"957"}
I have an input tag on the page called
<input class="avatar-src" name="avatar_src" type="hidden" value="">
Using jquery, I would like to store the value for "id" from the json string in the value attribute of my input tag.
There is a JS script that is already processing the "state", "message" and "result" objects from the json string. If possible I would like to leave that script alone and use a separate one to extract the JSON object "id". How would I do this?
Here is part of the first ajax response that manages "state" "message" and "result"
ajaxUpload: function () {
var url = this.$avatarForm.attr("action"),
data = new FormData(this.$avatarForm[0]),
_this = this;
$.ajax(url, {
type: "post",
data: data,
processData: false,
contentType: false,
beforeSend: function () {
_this.submitStart();
},
success: function (data) {
_this.submitDone(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
_this.submitFail(textStatus || errorThrown);
},
complete: function () {
_this.submitEnd();
}
});
},
syncUpload: function () {
this.$avatarSave.click();
},
submitStart: function () {
},
submitDone: function (data) {
console.log(data);
try {
data = $.parseJSON(data);
} catch (e) {};
if (data && data.state === 200) {
if (data.result) {
this.url = data.result;
if (this.support.datauri || this.uploaded) {
this.uploaded = false;
this.cropDone();
} else {
this.uploaded = true;
this.$avatarSrc.val(this.url);
this.startCropper();
}
this.$avatarInput.val("");
} else if (data.message) {
this.alert(data.message);
}
} else {
this.alert("Failed to response");
}
},
Assuming this is actually JSON, you'd have to parse it first... For instance, say your JSON was linked to a reference (variable):
var myJSON = '{"state":200,"message":null,"result":"..\/0images\/listimg\/orig\/54ab4719bf848.jpeg","id":"957"}';
From here, you'd have to parse the JSON into a JavaScript object with JSON.parse:
var myJSON = JSON.parse(myJSON);
Then, from here you can select the values as a JavaScript object.
$(".avatar-src").val(myJSON.id);
It would be best to start by giving your input tag an ID attribute AS WELL AS a name attribute so it can be uniquely referenced.
So whatever var you populate with the JSON object (let's just call it: var jSn):
<input id="avatar_src" name="avatar_src" class="avatar-src" type="hidden" value="">
<script>
$('#avatar_src').val(jSn.id);
</script>

Autocomplete with json data

I have two problems with this code:
json example:
{"json_list": [{"label": "Porto Rico", "value": 33}, {"label": "Portugal", "value": 32}]}
$("#user_country_name").autocomplete({
source : function(request, response) {
$.getJSON("/users/autocomplete/" + request.term, function(data) {
response(data.json_list);
});
},
});
First when I choose a country the selected value in the input box should be the label and not the value. Because the user should see the country and not the id.
Second, how can I populate the hidden field $("#user_country_id") for the id of the chosen country?
Use the select method
select: function( event, ui ) {
event.preventDefault();
$("#user_country_name").val(ui.item.label);
}
What you need to do, is to parse the json response. if you have any problems to get access use console.log().
$( "#w-arrival-search" ).autocomplete({
select: function (e, ui) {
$("#w-arrival-search").val(ui.item.label);
return false;
},
minLength: 3,
source: function (request, response) {
$.ajax({
url: 'http://localhost:8080/mvn/autocomplete',
data: request,
success: function (data) {
var ParsedObject = $.parseJSON(data);
response($.map(ParsedObject, function (item) {
var results = item.iata_code + " - " + item.city_name;
return {
label: results
};
}));
}
});
}
});

How to get the $(this) to work in JQueryUI autocomplete

Here is a fiddle example
I have trouble getting the $(this) to work in the source function with jQueryUI autocomplete.
The console shows that the search input isn't able to get its data attribute 'name' before sending out an Ajax request. Is there any way to pass the variable "name" to data?
$('.input').autocomplete({
source: function (request, response) {
var name = $(this).data('name');
console.log(name);
$.ajax({
url: url,
dataType: "json",
data: {
'q': request.term,
'field': name
},
success: function (data) {
response($.map(data.query.results.json.json, function (item) {
return {
label: item.name,
}
}));
}
});
},
minLength: 2,
select: function (event, ui) {
$(this).val(ui.item.label);
$(this).val(ui.item.label);
},
open: function () {
$(this).autocomplete("widget").width(400)
}
});
You should use this.element to access corresponding input element. this points to the autocomplete instance itself:
var name = $(this.element).data('name');

Select2 retrieving invalid results from the last selected select box

I am currently having an issue right now where my select2 plugin is showing results from the last selected select box sometimes. Also I also get g.results is null sometimes when I first click the select box or if I type too fast. My code is as follows.
window.currentField = ""; //current product field data
window.currentCategory = ""; //current product category data
//lets get some data from the hidden input for providing suggestions via ajax
$(".suggestive-entry").live('click',function() {
//alert("click called");
//alert("test");
window.currentField = $(this).siblings('input:hidden').attr('data-field'); //get the field attribute
// alert(window.currentField);
window.currentCategory = $(this).siblings('input:hidden').attr('data-category'); //get the category attribute
});
//formats select2 returned option
function format(item) { return item.term; };
//used for suggestive search fields
$(".suggestive-entry").select2({
createSearchChoice:function(term, data) { if ($(data).filter(function() { return this.term.localeCompare(term)===0; }).length===0) { return {id:term, term:term};} },
initSelection : function (element, callback) {
var data = {id: element.val(), term: element.val()};
callback(data);
},
multiple: false,
ajax: {
url: "includes/ajax/map-fields.php",
dataType: 'json',
data: function (term, page) {
//alert("suggestive called");
return {
q: term,
field: window.currentField,
ptype: window.currentCategory
};
},
results: function (data, page) {
return { results: data };
}
},
formatSelection: format,
formatResult: format
});
Any help would be greatly appreciated.
try to give id to your hidden field, do something like this
data: function (term, page) {
//alert("suggestive called");
var data_field = $('#someId').attr('data-field');
var data_category = $('#someId').attr('data-category');
return {
q: term,
field: data_field,
ptype: data_category
};
}

Categories