How to update a server side datatable on change a checkbox from outside of datatable - grails

I am using data table with Grails. I have a check box outside the data table and on its event I want to load the table again with the check box value. Here are my attempts below :
In my view where the check box is >>
<g:checkBox id="wrapCheck" name="wrapCheck"/> Wrapped
Here is my attempts in view where I am calling server method >>
$('#wrapCheck').on('click', function (e) {
setWrapActiveStatus();
var referenceId = $('#callForWrap').val();
jQuery.ajax({
type: 'POST',
dataType: 'JSON',
url: "${g.createLink(controller: 'androidGame',action: 'ajaxAndroidGameList')}?wrapCheck=" + referenceId,
%{--url: "${g.createLink(controller: 'androidGame',action: 'ajaxListByWrapActiveStatus')}?wrapCheck=" + referenceId,--}%
success: function (data, textStatus) {
if (data.isError == false) {
$('#example').DataTable().ajax.reload();
} else {
alert(data.message);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
}
});
});
here is my setWrapActiveStatus() function >>
function setWrapActiveStatus(){
if($("#wrapCheck").prop('checked') == true){
$('#callForWrap').val("1");
}else{
$('#callForWrap').val("");
}
}
And here is my Controller Action >>
def ajaxAndroidGameList() {
LinkedHashMap gridData
String result
LinkedHashMap resultMap = androidGameService.androidGamePaginateList(params)
if(params.wrapCheck == "1"){
resultMap = androidGameService.androidGamePaginateListByWrapStatus(params)
}
// LinkedHashMap resultMap = androidGameService.androidGamePaginateList(params)
if(!resultMap || resultMap.totalCount== 0){
gridData = [iTotalRecords: 0, iTotalDisplayRecords: 0, aaData: []]
result = gridData as JSON
render result
return
}
int totalCount = resultMap.totalCount
gridData = [iTotalRecords: totalCount, iTotalDisplayRecords: totalCount, aaData: resultMap.results]
result = gridData as JSON
render result
}
My action is response well only wrapped list but data table does not update.
EDIT - Data table Initialization
$('#example').dataTable({
"sPaginationType": "full_numbers",
"bAutoWidth": true,
"bServerSide": true,
"iDisplayLength": 10,
"deferLoading": ${totalCount?:0},
"sAjaxSource": "${g.createLink(controller: 'androidGame',action: 'ajaxAndroidGameList')}",
"fnRowCallback": function (nRow, aData, iDisplayIndex) {
if (aData.DT_RowId == undefined) {
return true;
}
$('td:eq(4)', nRow).html(getStatusIcon(nRow, aData[4])).css({textAlign: 'center'});
$('td:eq(5)', nRow).html(getStatusIcon(nRow, aData[5])).css({textAlign: 'center'});
$('td:eq(6)', nRow).html(getActionBtn(nRow, aData)).css({textAlign: 'center'});
return nRow;
},
"aoColumns": [
null,
{ "bSortable": false },
{ "bSortable": false },
{ "bSortable": false },
{ "bSortable": false },
{ "bSortable": false },
{ "bSortable": false }
]
});

In your DataTables initialization code you need to use option fnServerParams to modify data sent to the server.
I have also corrected deferLoading which should be iDeferLoading, see iDeferLoading.
Below is modified DataTables initalization code:
$('#example').dataTable({
"sPaginationType": "full_numbers",
"bAutoWidth": true,
"bServerSide": true,
"iDisplayLength": 10,
"iDeferLoading": ${totalCount?:0},
"sAjaxSource": "${g.createLink(controller: 'androidGame',action: 'ajaxAndroidGameList')}",
"fnServerParams": function (aoData){
aoData.push({
"name": "wrapCheck",
"value": $("#wrapCheck").prop('checked') ? "1" : ""
});
},
"fnRowCallback": function (nRow, aData, iDisplayIndex) {
if (aData.DT_RowId == undefined) {
return true;
}
$('td:eq(4)', nRow).html(getStatusIcon(nRow, aData[4])).css({textAlign: 'center'});
$('td:eq(5)', nRow).html(getStatusIcon(nRow, aData[5])).css({textAlign: 'center'});
$('td:eq(6)', nRow).html(getActionBtn(nRow, aData)).css({textAlign: 'center'});
return nRow;
},
"aoColumns": [
null,
{ "bSortable": false },
{ "bSortable": false },
{ "bSortable": false },
{ "bSortable": false },
{ "bSortable": false },
{ "bSortable": false }
]
});
Then for checkbox click event handler all you need to do is:
DataTables 1.10
$('#wrapCheck').on('click', function (e) {
$('#example').DataTable().ajax.reload();
});
DataTables 1.9
$('#wrapCheck').on('click', function (e) {
$('#example').dataTable().fnDraw();
});
NOTE:
Please note, that your DataTables initialization code and server-side code are using older naming conventions for DataTables 1.9. DataTables 1.10 is backward compatible, meaning that it supports both new and old naming conventions. But with the release of new versions, the compatibility may be dropped, and you may want to consider updating your code according to 1.9 to 1.10 upgrade guide and Converting 1.9 naming to 1.10.

Related

Select2 Version 4.0.1 upgrade initSelection

I have been using Select2 version 3 for my dropdowns for a while. However, I am trying to upgrade to the latest v4 release and am struggling to understand their documentation. Would someone be able to point me in the right direction in converting the below v3.5 code to v4 so that I can understand how to convert the rest of my code?
$("##hp.ID").select2(
{
dropdownAutoWidth: true,
minimumInputLength: 0,
allowClear: getBool("#hp.bAllowClear"),
width: "#hp.Width",
formatResult: formatResults,
formatSelection: formatSelection,
matcher: SetMatcher,
sortResults: SortSelect2,
initSelection: function (element, callback)
{
var id = "#Model"
if ((id != "") && (id != "0") && (id != undefined))
{
$.ajax("#Url.Action("GetVendorsInit", "DropDownManagerAjax")",
{
data: JSON.stringify({ VendorID: id }),
dataType: "json"
}).done(function (data)
{
callback({ id: data.id, text: data.text });
});
}
},
ajax: {
url: "#Url.Action("GetVendors", "DropDownManagerAjax")",
dataType: 'json',
quietMillis: 250,
data: function (term, page)
{
return {
q: term,
iDisplayStart: (page - 1) * 100,
iDisplayLength: 100,
sEcho: 0,
iSortCol_0: 0,
sSortDir_0: 'asc',
};
},
results: function (data, page)
{
var more = (page * 30) <= data.total;
return { results: data.data, more: more };
},
cache: true
},
dropdownCssClass: "autoWidth",
escapeMarkup: function (m) { return m; },
placeholder: 'Select Vendor...'
});

(Version 4.0.0-beta.3) 'more' feature for remote date loading stopped working

I just upgraded my select2 to the latest version in the subject and noticed that more loading stopped working.
select.select2({
placeholder: select.data("placeholder"),
allowClear: true,
multiple: select.attr('multiple') ? true : false,
ajax: {
url: '/Common/GetEntityItems',
dataType: 'json',
delay: 250,
data: function(term, page) {
return {
searchTerm: term,
page: page
};
},
processResults: function (data) {
var more = true;
return { results: data.items, more: more };
},
error: function (e) {
alert('error!');
},
formatResult: function (item) {
return '<div>' + item.text + '</div>';
},
formatSelection: function (item) {
return item.text;
}
}
});
Despite the unconditional true to more variable, more thing doesn't work any more. Do you see anything I am missing?
Brad,
in case you still looking for answer (it took me a couple of hours btw), you need to change
return { results: data.items, more: more };
to
return { results: data.items, pagination: { more: more } };
/Fred

Tweaking contextmenu in jstree

I would like to do the following with the contextmenu plugin:
- Rename "Create" as "Add"
- Remove "Edit"
How does one do it?
I do NOT want to create a custom menu because then I only get a node and not the nice data object that can be used in the Create, Rename and Delete events.
Found the answer in the code of jstree itself:
Added this to the jstree code:
"contextmenu": {
items: customContextMenu
}
And this for the context menu items:
function customContextMenu() {
'use strict';
var items = {
"create" : {
"separator_before": false,
"separator_after": true,
"_disabled": false, //(this.check("create_node", data.reference, {}, "last")),
"label": "Add",
"action": function (data) {
var inst = $.jstree.reference(data.reference),
obj = inst.get_node(data.reference);
inst.create_node(obj, {}, "last", function (new_node) {
setTimeout(function () { inst.edit(new_node); }, 0);
});
}
},
"rename" : {
"separator_before": false,
"separator_after": false,
"_disabled": false, //(this.check("rename_node", data.reference, this.get_parent(data.reference), "")),
"label": "Rename",
"action": function (data) {
var inst = $.jstree.reference(data.reference),
obj = inst.get_node(data.reference);
inst.edit(obj);
}
},
"remove" : {
"separator_before": false,
"icon": false,
"separator_after": false,
"_disabled": false, //(this.check("delete_node", data.reference, this.get_parent(data.reference), "")),
"label": "Withdraw",
"action": function (data) {
var inst = $.jstree.reference(data.reference),
obj = inst.get_node(data.reference);
if (inst.is_selected(obj)) {
inst.delete_node(inst.get_selected());
} else {
inst.delete_node(obj);
}
}
}
};
return items;
}

Delete, No url is set in jqgrid

I'm using jqgrid and when deleting a row in the grid i get the alert "Delete selected record?" and when i click ok i have written a code in onClickSubmit to make a ajax call to the controller which takes some parameters and delete the record. The functionality works fine.
But when i click "Delete" button in the alert i get an error "No url is set". Now, i have a url inside my ajax call which does the function. Why is the error thrown?
jqGrid:
var selectedRowId = "125";
$("#AttachmentsGrid").jqGrid({
url: '#Url.Action("LoadTransactionAttachments", "Home")',
postData: { 'transactionId': selectedRowId },
mtype: 'GET',
datatype: 'json',
jsonReader: {
id: 'AttachmentId',
repeatitems: false
},
height: 'auto',
hidegrid: false,
rownumbers: true,
autowidth: true,
shrinkToFit: false,
rowNum: 10,
pager: '#AttachmentsPager',
caption: "Attachments",
colNames: ['AttachmentName'],
colModel: [{ name: 'AttachmentName', index: 'AttachmentName', formatter: imageFormatter, unformat: imageUnFormatter }],
beforeRequest: function () {
responsive_jqgrid($(".jqGrid"));
},
onSelectRow: function (id) {
var statusId;
attachmentId = id;
var selectValues = jQuery('#AttachmentsGrid').jqGrid('getRowData', id);
attachmentName = selectValues.AttachmentName;
if (accessLevel.HasDeleteAttachmentAccess == true)
$("#del_AttachmentsGrid").show();
else
$("#del_AttachmentsGrid").hide();
},
loadComplete: function () {
UnBlockUI();
}
});
jQuery("#AttachmentsGrid").jqGrid('navGrid', '#AttachmentsPager', {
edit: false, add: false, del: true, search: false, refresh: true, refreshtext: ""
}, {}, {}, {
// url: '#Url.Action("UpdateDummyData", "Home")',
// Delete attachment event.
onclickSubmit: function (response, postData) {
$.ajax({
url: '#Url.Action("DeleteSelectedTransactionAttachment", "Home")',
datatype: 'json',
data: { 'attachmentId': JSON.stringify(postData), 'attachmentName': attachmentName, 'transactionId': selectedRowId },
type: 'POST',
success: OnCompleteDeleteAttachments,
error: function (xhr, status, error) {
if (xhr.statusText == "Session TimeOut/UnAuthorized") {
alert(xhr.statusText);
window.location.href = '#Url.Action("LogOut", "Account")';
}
else
alert(xhr.responseText);
}
});
It works when i give some Dummy url in delete method which i dont need. I need another way to solve this.?
FYI, This happens for me also during the edit of a row using form editing.
It seems to me that you try to use Delete in a wrong way. What you do is making Ajax request to '#Url.Action("DeleteSelectedTransactionAttachment", "Home")' with some additional data, do some unknown additional action inside of OnCompleteDeleteAttachments in case of successful deleting and do additional error handling in case of "Session TimeOut/UnAuthorized" error in statusText.
I think that correct implementation should looks more as the following
jQuery("#AttachmentsGrid").jqGrid('navGrid', '#AttachmentsPager', {
edit: false, add: false, search: false, refreshtext: ""
}, {}, {}, {
url: '#Url.Action("DeleteSelectedTransactionAttachment", "Home")',
serializeDelData: function (postData) {
return {
attachmentId: JSON.stringify(postData),
attachmentName: attachmentName,
transactionId: selectedRowId
}
},
errorTextFormat: function (xhr) {
if (xhr.statusText == "Session TimeOut/UnAuthorized") {
window.location.href = '#Url.Action("LogOut", "Account")';
} else {
return xhr.responseText;
}
},
afterSubmit: OnCompleteDeleteAttachments
});

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

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.

Resources