Autocomplete in Jqgrid returns Data from Server but dont know to put in View - jquery-ui

This is my first post. stackoverflow is a wonderful place for developers. Here is my issue.
I am trying to use Autocomplete in JqGrid Edit Form. i successfully retrieved data from server using ajax call but dont know how to display it in the view. below is my code.
FrontEnd Code:
colModel :[
{name:'prf_articlename', index:'prf_articlename', width:90, editable:true, edittype:'text',
editoptions: {
dataInit:function(e){
$(e).autocomplete({
source: function(request, response,term) {
var param = request.term;
$.ajax({
url: '/Myelclass/AutoCompleteServlet.do?term='+param+"&action="+"artname",
success: function (data) {
response($.map(data, function(item) {
return {
label: item.label,
};
}));//END Success
},
});//END AJAX
},
minLength: 2,
});//END AUOTOCOMPLETE
}//END Dataint
}//END Dataint
},
BackEnd Code:
String term = request.getParameter("term");
List<AutoComplete> articlelist = prfbo.getArticleNameinEditGrid(term);
System.out.println("List Value " +articlelist.size());
JSONArray jsonOrdertanArray = JSONArray.fromObject(articlelist);
System.out.println(jsonOrdertanArray);
out.println(jsonOrdertanArray);
Any one help on this???

This is what I personally use in my project:
Inside colModel:
dataInit: function (elem) { NameSearch(elem) }},
The function:
function NameSearch(elem) {
$(elem).autocomplete({ source: '/Controller/NameSearch',
minLength: 2, autosearch: true,
select: function (event, ui) {
$(elem).val(ui.item.value);
$(elem).focus().trigger({ type: 'keypress', charCode: 13 });
}
})//$(elem).autocomplete
$(elem).keypress(function (e) {
if (!e) e = window.event;
if (e.keyCode == '13') {
setTimeout(function () { $(elem).autocomplete('close'); }, 500);
return false;
}
})//$(elem).keypress(function (e){
} //function NameSearch(elem) {
I'm also dealing with an Enter key press as well in the above function.

here is the complete code for my Autocomplete in jqgrid Edit form..
colModel :[
{name:'name', index:'name', width:90, align:'center', editable:true, hidden: false, edittype:'text',
editoptions:{
dataInit:function (elem) {
$(elem).autocomplete({
minLength: 2,
source: function(request, response,term) {
var param = request.term; //values we enter to filter autocomplete
$.ajax({
url: "myurl",
dataType: "json",
type:"GET",
success: function (data) {
response($.map(data, function(item) {
return {
//can add number of attributes here
id: item.id,
shform: item.shortform,
value: item.name,
clr : item.color, //here apart from name and id i am adding other values too
size: item.size,
remar:item.remarks,
subs: item.subs,
selec:item.selec ,
};
}));//END Response
},//END Success
});//END AJAX
},
select: function( event, ui ) {
// setting values to textbox in jqgrid edit form based on selected values
$('#textbox1').val(ui.item.id);
$('#textbox2').val(ui.item.shform);
$('#textbox3').val(ui.item.clr);
$('#textbox4').val(ui.item.size);
$('#textbox5').val(ui.item.sizeremar);
$('#textbox6').val(ui.item.subs);
$('#textbox7').val(ui.item.selec);
$('#textbox8').val(ui.item.selp);
}
});
$('.ui-autocomplete').css('zIndex',1000); // if autocomplete has misalignment so we are manually setting it
}
}, editrules :{required : true},
formoptions:{rowpos: 1, colpos: 2}
},
........
]
server code :
String term = request.getParameter("term");
List<ArticleDetails> articlelist = prfbo.getPrfArticleName(term); //DB call via BO and DAO class
System.out.println("List Value " +articlelist.size());
JSONArray jsonOrdertanArray = JSONArray.fromObject(articlelist);
System.out.println(jsonOrdertanArray);
out.println(jsonOrdertanArray);
hope some one find it useful.

Related

How can I get the selected checkbox in kendo grid?

I have Kendogrid grid that I get the data by JSON for the URL that I have and activate Selection mode as I found the kendo grid documentation, but I am trying to get the selected data from kendo grid, try some methods in javascript but not yet I have been able to do it. If someone can help me?
$(document).ready(function () {
$("#grid").kendoGrid({
toolbar: ["excel"],
excel: {
fileName: "user.xlsx",
filterable: true
},
dataSource: {
transport: {
read: {
url: `/user`
}
},
schema: {
data: function (response) {
return response.permisos;
},
model: {
fields: {
id: { type: "number" },
nombre: { type: "string" },
descripcion: { type: "string" }
}
}
},
pageSize: 20
},
height: 550,
scrollable: false,
sortable: true,
filterable: true,
pageable: true,
persistSelection: true,
change: onChange,
columns: [
{ selectable: true, width: "50px" },
{ field: "id", title: "Id" },
{ field: "nombre", title: "Nombre" },
{ field: "descripcion", title: "DescripciĆ³n" }
]
});
$("#grid").data("kendoGrid").wrapper.find(".k-grid-header-wrap").off("scroll.kendoGrid");
});
I found two solutions, the first one is activating the change: onchange, one can obtain the selected checkboxes, each time one selects. What I'm doing is going through the checkboxes and saving them in a list
function onchange(e) {
var permiso = [];
var numero = 0;
var rows = e.sender.select();
rows.each(function (e) {
var grid = $("#grid").data("kendogrid");
var dataitem = grid.dataitem(this);
var recibir = dataitem;
console.log(dataitem);
console.log("dato recibido" + recibir.id);
permiso.push(recibir.id);
})
console.log("largo: " + permiso.length);
for (var i = 0; i < permiso.length; i++) {
console.log("array: " + permiso[i]);
}
And the other way is that you added a button that activates the event to go through the grid to get the checkbox, which is the best for me
$("#saveChanges").kendoButton({
click: function (e) {
var permiso = [];
var entityGrid = $("#grid").data("kendoGrid");
var rows = entityGrid.select();
rows.each(function (index, row) {
var selectedItem = entityGrid.dataItem(row);
var recibir = selectedItem;
console.log(selectedItem);
console.log("Dato recibido rows.each" + recibir.id);
permiso.push(recibir.id);
});
for (var i = 0; i < permiso.length; i++) {
console.log("List obtenido por el boton: " + permiso[i]);
}
var RolPermisos = { rolId: $("#IdRol").val() , permisos: permiso };
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: '../../Roles/api/Ui/',
dataType: 'json',
data: $.toJSON(lineItems),
success: function (result) {
if (result) {
alert('Success');
}
else {
alert('Failure');
}
}
});
}
})
My English is not so good, I hope you get the answer.

How to avoid multiple ajax call from the Jquery Autocomplete ? Using Cache

I am using jquery automcomplete with the Ajax call but what i want is if part is present in the json data fetched by the ajax on first call then i want to return that data as it is without giving the ajax call i have tried it as below
function SearchText() {
var cache = {};
$("#txtItem").autocomplete({
source: function (request, response) {
var term = request.term;
$.each(cache, function (index, value) {
$.each(value, function (index, value) {
if (value.indexOf(term) >= 0) {
response(cache[term]);
return;
}
});
});
cache = {};
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "JobTagPricing.aspx/GetAutoCompleteData",
data: "{'item':'" + document.getElementById('txtItem').value + "'}",
dataType: "json",
success: function (data) {
cache[term] = data.d;
response(data.d);
},
error: function (result) {
alert("Error");
}
});
},
minLength: 3
});
}
but even if it finds the matching term in the array then also it generates the ajax call.
I m stuck here for 3 hrs now any help would be great. I have tried maxCacheLength but it is also not working.
Try this out, sometime ago i faced same problem and came up with this it might work for you
function SearchText() {
var cache = {};
var oldterm;
$("#txtItem").autocomplete({
source: function (request, response) {
if (request.term.indexOf(oldterm) >= 0) {
if (typeof (oldterm) != 'undefined') {
var data = jQuery.grep(cache[oldterm],
function (ele) {
return (ele.indexOf(request.term) >= 0);
});
response($.map(data, function (item) {
return { value: item }
}))
return;
}
} else {
cache = {};
$.ajax({
url: "JobTagPricing.aspx/GetAutoCompleteData",
data: "{ 'item': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
oldterm = request.term;
cache[request.term] = data.d;
response($.map(data.d, function (item) {
return {
value: item
}
}))
},
error: function (result) {
alert("Error");
}
});
}
},
minLength: 3,
select: function (event, ui) {
if (ui.item) {
formatAutoComplete(ui.item);
}
}
});
}
Here is a solution i found for you, It uses jQuery UI's autocomplete using cache and $.map function
function SearchText() {
var cache = {};
$("#textbox").autocomplete({
source: function(request, response) {
if (request.term in cache) {
response($.map(cache[request.term].d, function(item) {
return { value: item.value, id: item.id }
}))
return;
}
$.ajax({
url: "JobTagPricing.aspx/GetAutoCompleteData",
data: "{ 'term': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json",
dataFilter: function(data) { return data; },
success: function(data) {
cache[request.term] = data;
response($.map(data.d, function(item) {
return {
value: item.value,
id: item.id
}
}))
},
error: HandleAjaxError
});
},
minLength: 3,
select: function(event, ui) {
if (ui.item) {
formatAutoComplete(ui.item);
}
}
});
}
Hope this helps.

jqxgrid not displaying busy or loading indicator

I am using jqxgrid and I have below code snippet and i want to display load indicator on button click which calls the Ajax method and hide it on the success method or anyway other to display it as i need to show loading indicator from the time request made till i get the data
$("#btnSearch").bind('click', function () {
//show indicator here
LoadLookUpSearchGrid();
}
//Ajax call to fetch data
function LoadLookUpSearchGrid() {
var filterRows = getGridRows();
$.ajax({
type: 'POST',
dataType: 'json',
async: false,
cache: false,
url: 'AddEditView.aspx/LoadLookUpSearchGrid',
data: JSON.stringify({ FilterType: $('select#ddlFilterType').val() , Id: $("#txtId").val() , Name: $("#txtName").val(), SearchText: '', FilterRows: filterGridRows}),
contentType: 'application/json; charset=utf-8',
success: function (data) {
var source = data.d;
SetSearchFields($('select#ddlFilterType option:selected').text(), source);
},
error: function (err) {
alert(err.text + " : " + err.status);
}
});
};
//source object to format data
function SetSearchFields(fieldName, source) {
var columns;
if (fieldName == "Operating Company") {
source =
{
datatype: "xml",
datafields: [
{ name: 'COMPANY', type: 'string' },
{ name: 'DESCR', type: 'string' }
],
async: false,
root: "Company",
localdata: source
};
columns = [
{ text: 'OPCO ID', dataField: 'COMPANY', width: '30%' },
{ text: 'Company Name', dataField: 'DESCR', width: '65%' }
];
}
lookupSearchResultGrid(source, columns,fieldName);
}
//adaptor to fill source and bind grid
function lookupSearchResultGrid(source, columns,fieldName) {
var searchViewGridDataAdapter = new $.jqx.dataAdapter(source);
$("#divLookupSearch").jqxGrid(
{
width: '100%',
source: searchViewGridDataAdapter,
theme: theme,
sortable: true,
pageable: true,
autoheight: true,
selectionmode: 'checkbox',
columns: columns
});
//hide indicator here on on success method of ajax call
};
On the click of the button call showloadelement and in the Ajax call success callback function call hideloadelement.
$("#btnSearch").bind('click', function () {
$('#divLookupSearch').jqxGrid('showloadelement');
//show indicator here
LoadLookUpSearchGrid();
}
...
success: function (data) {
$('#jqxGrid').jqxGrid('hideloadelement');
var source = data.d;
SetSearchFields($('select#ddlFilterType option:selected').text(), source);
},
...
Best Regards,
Alpesh

JQueryAutoComplete Not showing results

I am trying to bind the text box and the JQuery AutoComplete feature. When I checked the Firebug AJAX Request & Response it returns like the following. But the textbox is not showing any items. Could you please advise me, what I am doing wrong? Thanks.
Here is my coding:
$("#<%= TextBox1.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
url: "/contractors/web_services/wsSM.asmx/SearchDrugs",
type: "POST",
dataType: "json",
data: {
'LocationID': "10543",
'Search': request.term
},
success: function (data) {
response($.map(data.d, function (item) {
return {
value: item.FullDrugName,
id: item.DrugID
}
}))
}
});
},
delay: 1,
minLength: 2,
select: function (event, ui) {
alert(ui.item.id);
}
});
DataType property is representing the type of data that you're expecting back from the server.
you define data type as json but server returns you a xml output. You should change your DataType property to xml
In addition to #fealin's answer, you're going to need to change the way you process the xml response. It doesn't look like you have a d property on the return data, and you also need to look for the correct nodes in the XML structure and pull out their text to build the response array that you return to the widget.
Based on the XML you've provided, it might look something like this:
$("#<%= TextBox1.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
url: "/contractors/web_services/wsSM.asmx/SearchDrugs",
type: "POST",
dataType: "json",
data: {
'LocationID': "10543",
'Search': request.term
},
success: function (data) {
response($(data).find("Drug").map(function (_, el) {
var $el = $(el);
return {
label: $el.find("FullDrugName").text(),
value: $el.find("DrugID").text()
};
}));
});
},
delay: 1,
minLength: 2,
select: function (event, ui) {
alert(ui.item.id);
}
});
Here's an example that's just using the XML string (without an AJAX request): http://jsfiddle.net/J5rVP/29/

JQuery Autocomplete source is a function

I'm using JQuery UI autocomplete, for different fields. To get the data i'm using a function as the source. It work great!
I was wondering if there were a way of not using the anonym function in the source, but to declare a generic one which will have a parameter to redirect to the right URL.
I'm quite new in JS and JQuery and so I have no idea of what the parameters request and response are comming from in the anonym function.
Here is what I'm trying to do:
$ac.autocomplete({
//Call the function here, but what are the parameter request and response???
source: autocomplete(),
minLength: 1
});
Here is the function I'd like to call
function autoComplete(request, response, url) {
$.ajax({
url: '/Comp/'+url,
dataType: "json",
type: "POST",
success: function (data) {
response($.map(data, function(item) {
return { label: item, value: item, id: item };
}));
}
});
}
Thanks a lot for your help.
You should use
source: autoComplete
instead of
source: autocomplete()
One more remark. The default implementation of jQuery UI Autocomplete use only value and label and not use id.
Reformatting ur question will pose as solution to the problem .:)
$ac.autocomplete({
minLength: 1 ,
source: function(request, response, url){
var searchParam = request.term;
$.ajax({
url: '/Comp/'+url,
data : searchParam,
dataType: "json",
type: "POST",
success: function (data) {
response($.map(data, function(item) {
return {
label: item.Firstname,
value: item.FirstName
};
});
}
});//ajax ends
}
}); //autocomplete ends
The request and response objects are expected by jQuery UI . The request.term will give u the text that the user types and the response method will return the label and value items to the widget factory for displaying the suggestion dropdown
P.S : assuming ur JSON string contains a FirstName key !
I will give an example of a situation that happened to me, might serve as an example:
Situation: After the user selects a keyword with Jquery Autocomplete not allow it to be listed. Taking into account that the query is executed the same, ie the unamended cat. server-side.
The code looked like this:
$( "#keyword-search" ).autocomplete({
minLength: 3 ,
source: function( request , response ) {
var param = { keyword_type: type , keyword_search: request.term } ;
$.ajax({
url: URI + 'search-to-json',
data : param,
dataType: "json",
type: "GET",
success: function (data) {
response($.map(data, function( item ) {
/* At this point I call a function, I use to decide whether to add on the list to be selected by the user. */
if ( ! is_record_selected( item ) ) {
return item;
}
}));
}
});
} ,
select: function( event , ui ) {
/* Before you add, looking if there is any cell */
/* If it exists, compare the id of each cell not to add an existing */
if ( validate_new_keyword( ui ) ) {
add_cell( ui ) ;
}
} ,
});
/* Any validation... */
function validate_new_keyword( ui ) {
var keyword_id = $.trim(ui.item.id) ;
Any condition...
if (keyword_id > 0) {
return true ;
}
return false ;
}
/* This function checks if a keyword has not been selected by the user, it checks for the keyword_array. */
function is_record_selected( item ) {
var index = jQuery.inArray( item.id , keyword_array ) ;
return index == -1 ? false : true;
}
Obs: Thus it is possible to use a function inside "source" and "select". =p

Resources