Populate JQuery DataTable with my json data - javascript

I'm suggested to use JQuery data table. Now I need to populate grid with bunch of json objects sent from my controller. How can I send this data on the grid from js
$.ajax({
...
url: '/Home/ReturnJsonData',
success: function (result) {
$.each(result, function (i, item) {
// this is where I should sent item object to my grid
});
},
error: function () { alert("error"); }
});
Update
I've found these link, but I dont know how to implement it.

You should use JQuery DataTable sAjaxSource property to specify ajaxsource in your case it would be /HomeReturnJsonData
An example follow
$(document).ready(function () {
$('#myDataTable').dataTable({
"bServerSide": true,
"sAjaxSource": "Home/ReturnJsonData",
"bProcessing": true,
"aoColumns": [
{ "sName": "ID",
"bSearchable": false,
"bSortable": false,
"fnRender": function (oObj) {
return '<a href=\"Details/' +
oObj.aData[0] + '\">View</a>';
}
},
{ "sName": "COMPANY_NAME" },
{ "sName": "ADDRESS" },
{ "sName": "TOWN" }
]
});
});

You can use Jquery Grid Plugin in that case.
Read this article to use MVC Data Grid: using jqGrid and JSON
http://blog.davidrenz.com/?p=663
Update:
In that case if you only want to use J-query Datatable go to this link.
http://www.codeproject.com/Articles/155422/jQuery-DataTables-and-ASP-NET-MVC-Integration-Part

I put this in a function because that was the easiest way to do it for me, feel free to copy the function and use it. All your going to need to change is the url and the column names and number there of. To call it just copy the html with the paths done so that they match whatever yours are.
function SetUpGrid(tableID, pagerID, data) {
$("#" + tableID).jqGrid({
url: '/pagename/stuff?data=' + data,
datatype: 'json',
mtype: 'GET',
colNames: ['col name1', 'col name2', ... 'col nameN'],
colModel: [
{ name: 'colName1', index: 'colName1', align: "center", sortable: true, editable: false, resizable: false },
{ name: 'colName2', index: 'colName2', align: "center", sortable: true, editable: false, resizable: false },
...
{ name: 'colNameN', index: 'colNameN', align: "center", sortable: true, editable: false, resizable: false }
],
pager: '#' + pagerID,
autowidth: true,
viewrecords: true,
rowNum: 15,
pgbuttons: true,
pginput: false,
pgtext: "Page {0} of {1}",
recordtext: "Data {0} - {1} of {2}",
emptyrecords: "No data to display",
loadui: true,
rowList: [15, 30, 60],
scrollrows: true,
hidegrid: true,
sortorder: "desc",
beforeRequest: function () { // This just inserts a loading image, you don't need it but I was loading a lot of data and wanted the user to know something was happening.
$("#" + tableID).empty().append('<tr><td><img src="/Content/imgs/loading.gif" /></td></tr>');
},
loadComplete: function (data) {
/*
Called when the json load is done, this is a way to insert the data the way I want to.
Feel free to use whatever you want like links or <p>s or <div>s or whatever.
*/
if (data.length > 1) {
for (var key in data) {
if (data.hasOwnProperty(key)) {
$("#" + tableID).empty().append("<tr><td>" + data[key].colName1 + "</td><td>" + data[key].colName12+ "</td> ... <td>" + data[key].colNameN + "</td></tr>");
}
}
} else {
$("#" + tableID).empty().append("<tr><td>" + this.colName1 + "</td><td>" + this.colName2 + "</td> ... <td>" + this.colNameN + "</td></tr>");
}
},
loadError: function (xhr, status, error) {
// Called when an error occurs, handle as you wish, if you even do.
alert(xhr);
alert(status);
alert(error);
}
});
$("#" + tableID).jqGrid("navGrid", "#" + pagerID, { add: false, edit: false, refresh: false, del: false, search: false }).trigger("reloadGrid", [{ page: 1 }]);
}
<script src="/Scripts/jquery-1.7.2.js"></script>
<script src="/Scripts/jquery-ui-1.8.23.min.js"></script>
<script src="/Scripts/jquery.jqGrid.min.js"></script>
<script src="/Scripts/grid.locale-en.js"></script>
<script src="/Scripts/ADTFunding.js"></script>
<link href="/Content/themes/base/jquery.ui.all.css" rel="stylesheet" type="text/css" />
<link href="/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(function () {
SetUpFundingGrid('dataTable', 'pager', '9895998');
});
</script>
<table id="dataTable"></table>
<div id="pager"></div>

You can also use the fnAddData property to push json to table. Check this article https://jqueryajaxphp.com/jquery-datatable-using-json/

Related

DataTable fixed header not working for scrollable table

I've been working with dataTables for a short period of time and I have a DataTable with two columns:
TableVehUsage = $("#TableVehUsage ").DataTable({
data: [],
ordering: true,
paginate: false,
"info": false,
fixedHeader: {header: true},
columns: [
{ data: "Vehicle", title: "Vehicle" },
{ data: "Serial", title: "Serial" }
],
"columnDefs": [
{
"targets": 0,
"render": function (data, type, full, meta) {
// If it is rendering the cell contents
if (type === 'display') {
switch (data) {
case "-":
return "-";
default:
if (full.IsOnSale == true)
return '<span style="color:red" onclick="ToParentTab(' + full.Id + ')">' + data + '</span>';
else
return '<span onclick="ToParentTab(' + full.Id + ')">' + data + '</span>';
}
}
return (isNaN(data)) ? -1 : +data;
}
} }]
});
I have some situation when all the data don't fit in the page and the user needs to scroll down to see all the info. I've tried to use Fixed Header by adding to my javascript the line fixedHeader: {header: true} and in the html:
<script src="https://cdn.datatables.net/fixedheader/3.1.2/js/dataTables.fixedHeader.min.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/fixedheader/3.1.2/css/fixedHeader.dataTables.min.css">
But is not working for me :(
What am I doing wrong?
I found a DataTable plugin that may be of help. Information on it is located at https://datatables.net/extensions/scroller/
Using this, my definition looks like this:
var table1 = $('#example').DataTable({ paging: true,   
scrollY:        200,
deferRender:    true,
scroller:       true });
I made a jsFiddle at https://jsfiddle.net/bindrid/oywvh1ek/6/
Try adding your data in a different variable with only the 'value' part of the key-value pair in it. For example, in the case of
{"vehicle":"Audi"},
your 'data' variable should have only ["Audi"] in it.
The below code worked perfectly for me.
$("<your_table_name>").DataTable({
data:data,
fixedHeader:true,
"scrollX": true,
"scrollY": "200px",
"scrollCollapse": true,
columns: [
{ title: 'Vehicle' },
{ title: 'Serial' }
]
});
I had a problem where my fixedHeader was working until I got about halfway down the page, then it disappeared. Here is what I did to get it working:
At the top of my JS file:
$(document).ready(function () {
DrawDataTable();
//This enables the table header to stick to the top of the page when the user is scrolling
var employeeData = $('#employee-table').DataTable();
employeeData.fixedHeader.adjust();
});
Then in the same JS file, in my jQuery ajax call, I had to add the line of code that says "fixedHeader": true
Finally, in my HTML file, I had to include the following in my <head> section:
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.12.1/fh-3.2.4/r-2.3.0/datatables.min.css"/>
<script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.12.1/fh-3.2.4/r-2.3.0/datatables.min.js"></script>
Do not forget that you will also need to include whatever Bootstrap, JavaScript or jQuery scripts or style sheets in the head as well.

JQGrid empty grid and no navigation or edit icons

For some reason, my grid is blank with no rows (not even an empty row), no navigation icons and no editing icons. I'm using a few add-in features such as an autocomplete field (inside the grid), and a font resizing script so my script is a bit long. The page is receiving the properly formatted response from my functions page and it seems to match my jsonReader settings but it's not populating the grid with it. Here is my JSON formatted response from the page:
{"page":"1",
"total":1,
"records":"4",
"rows":[{"DetailID":"1","Quantity":"2","TaskName":"Differencial With Housing","UnitPrice":"335.00","ExtendedPrice":"670.00"}, {"DetailID":"2","Quantity":"1","TaskName":"Left axel seal","UnitPrice":"15.00","ExtendedPrice":"15.00"},{"DetailID":"3","Quantity":"1","TaskName":"Upper and Lower Bearings","UnitPrice":"55.00","ExtendedPrice":"55.00"}, {"DetailID":"5","Quantity":"1","TaskName":"Fluids","UnitPrice":"45.00","ExtendedPrice":"45.00"}]}
And here is my grid script:
<script>
function autocomplete_element(value, options) {
var $ac = $('<input type="text"/>');
$ac.val(value);
$ac.autocomplete({source: "autocomplete.php?method=fnAutocomplete"});
return $ac;
}
function autocomplete_value(elem, op, value) {
if (op == "set") {
$(elem).val(value);
}
return $(elem).val();
}
$(document).ready(function()
{
$('#filter').jqm();
var selectedRow = 0;
$("#list").jqGrid(
{
url:'managegrid.php',
datatype: 'json',
colNames:['DetailID', 'ProjectID','Qty.','Description','Unit Price','Total Cost'],
colModel :[
{name:'DetailID', index:'DetailID', hidden:true, editable:false},
{name:'ProjectID', index:'ProjectID', width:25, hidden:true, editable:true},
{name:'Quantity', index:'Quantity', editable:true, width:50, align:'right', edittype:'text', editoptions: {defaultValue:'1'}},
{name:'TaskName', index:'TaskName', editable:true, width:450, align:'left', edittype: 'custom', editoptions: {'custom_element' : autocomplete_element, 'custom_value' : autocomplete_value}},
{name:'UnitPrice', index:'UnitPrice', editable:true, width:100, align:'right'},
{name:'ExtendedPrice', index:'ExtendedPrice', editable:false, width:100, align:'right'}
],
onSelectRow: function(id){
if(DetailID && DetailID!==mkinline){
jQuery('#list').saveRow(mkinline);
jQuery('#list').editRow(DetailID,true);
mkinline=DetailID;
}
},
pager: $('#pager'),
rowNum:20,
rowList:[],
pgbuttons: false,
pgtext: null,
sortorder: "asc",
sortname: "DetailID",
viewrecords: true,
imgpath: '/js/jquery/css/start/images',
caption: 'Project Details',
height:'auto',
width:823,
mtype:'GET',
recordtext:'',
pgtext:'',
editurl:"editgrid.php",
toolbar:[true,"bottom"],
loadComplete:function(){
var recorddata = $("#list").getUserData();
$("#t_list").html(recorddata.MSG);
},
jsonReader: {
page: "PAGE",
total: "TOTAL",
records:"RECORDS",
root: "ROWS",
userdata:"USERDATA"
}
}
);
$("#t_list").css("color","blue");
jQuery("#list").jqGrid("inlineNav",'#pager',{edit:true,editicon: "ui-icon-pencil",add:true,addicon: "ui-icon-plus",search:false}, {}, {},
{url:"delgridrow.php",closeAfterDelete:true,reloadAftersubmit:false,afterSubmit:commonSubmit,caption:"Delete",msg:"Delete selected",width:"400"})
.navButtonAdd('#pager',{caption:"",title:"Reload Form",buttonimg:'/js/jquery/css/start/images/refresh.gif',onClickButton:function(id)
{
resetForm();
$("#list").setGridParam(
{
url:"managegrid.php",
page:1
}
).trigger("reloadGrid");
}
});
}
);
function gridSearch()
{
var pid = $("#DetailID").val();
var qty = $("#Quantity").val();
var tn = $("#TaskName").val();
var up = $("#UnitPrice").val();
$("#list").setGridParam(
{
url:"managegrid.php?ProjectID="+pid+"&Quantity="+qty+"&TaskName="+tn+"&UnitPrice="+up,
page:1
}
).trigger("reloadGrid");
$("#filter").jqmHide();
return false
}
function commonSubmit(data,params)
{
var a = eval( "(" + data.responseText + ")" );
$("#t_list").html(a.USERDATA.MSG);
resetForm();
return true;
} function resetForm()
{
window.location.reload(false);
}
</script>
I've been trying to figure this one out all weekend and it's driving me crazy so any help would be appreciated.
You should add the line of code
jQuery("#list").jqGrid("navGrid", '#pager',
{add: false, edit: false, del: false, search: false, refresh: false});
directly before calling of inlineNav.
UPDATED: Your code have many other problems too. For example, you should remove jsonReader option from your code, because it contains wrong values of properties (like root: "ROWS" instead of root: "rows", which is default and can be removed). You can consider to use jsonReader: { id: 'DetailID' } to use the value of DetailID as the rowid and to use DetailID instead of id during editing. I'd recommend you to define all variables before the usage (see mkinline and DetailID for example).

Add/edit/delete a row in free jqGrid

I am using free jqGrid 4.12.1. I want to add, edit and delete rows in the grid and wish to make server side calls for each operation.
I have added editurl and 'actions' formatter as below,
{
name: "actions",
width: 100,
formatter: "actions",
formatoptions: {
keys: true,
editOptions: {},
addOptions: {},
delOptions: {}
}
}
I am adding 'inlineNav' as below,
$("#itemList").jqGrid('inlineNav',"#itemListPager",
{
edit: true,
add: true,
del: true,
search: true,
searchtext: "Search",
addtext: "Add",
edittext: "Edit",
deltext: "Delete"
},
{
closeOnEscape: true, //Closes the popup on pressing escape key
reloadAfterSubmit: true,
drag: true,
url: "${pageContext.request.contextPath}/billing/saveItem",
errorfunc: function (rowId, resp) {
alert(resp);
},
afterSubmit: function (response, postdata) {
if (response.responseText == "") {
$(this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid'); //Reloads the grid after edit
return [true, '']
}
else {
$(this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid'); //Reloads the grid after edit
return [false, response.responseText]//Captures and displays the response text on th Edit window
}
},
editData: {
EmpId: function () {
var sel_id = $('#itemList').jqGrid('getGridParam', 'selrow');
var value = $('#itemList').jqGrid('getCell', sel_id, '_id');
return value;
}
}
},
{
closeAfterAdd: true, //Closes the add window after add
url: "${pageContext.request.contextPath}/billing/saveItem",
afterSubmit: function (response, postdata) {
if (response.responseText == "") {
$(this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid')//Reloads the grid after Add
return [true, '']
}
else {
$(this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid')//Reloads the grid after Add
return [false, response.responseText]
}
}
},
{ //DELETE
closeOnEscape: true,
closeAfterDelete: true,
reloadAfterSubmit: true,
url: "${pageContext.request.contextPath}/billing/saveItem",
drag: true,
afterSubmit: function (response, postdata) {
if (response.responseText == "") {
$("#itemList").trigger("reloadGrid", [{ current: true}]);
return [false, response.responseText]
}
else {
$(this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid');
return [true, response.responseText]
}
},
delData: {
EmpId: function () {
var sel_id = $('#itemList').jqGrid('getGridParam', 'selrow');
var value = $('#itemList').jqGrid('getCell', sel_id, '_id');
return value;
}
}
},
{//SEARCH
closeOnEscape: true
}
);
The 'inlineNav' added above has no effect because no server side call is made on adding a new row or deleting existing row. The server side call is made only in case of edit, and that call too does not happen through 'inlineNav' code above. Because even if i remove 'inlineNav' code the server side call is still made to the 'editurl'.
So how can i make server side calls on adding/editing/deleting rows and also pass parameters to these calls. I will really appreciate if someone can point me to a working example somewhere. Thanks
UPDATE:-
I have removed 'actions' formatter and modified code to look as below,
<script type="text/javascript">
var dataGrid = $('#itemList');
var firstClick = true;
$(document).ready(function () {
$('#action').click(function () {
if (!firstClick) {
$("#itemList").setGridParam({datatype:'json'}).trigger("reloadGrid");
}
firstClick = false;
$("#itemList").jqGrid({
url: "${pageContext.request.contextPath}/billing/medicines",
datatype: "json",
//styleUI : 'Bootstrap',
mtype: "POST",
autowidth: true,
shrinkToFit: true,
sortname: "Id",
sortorder: "asc",
loadBeforeSend: function(jqXHR) {
jqXHR.setRequestHeader("X-CSRF-TOKEN", $("input[name='_csrf']").val());
},
postData: {
},
loadError: function (jqXHR, textStatus, errorThrown) {
alert('HTTP status code: ' + jqXHR.status + '\n' +
'textStatus: ' + textStatus + '\n' +
'errorThrown: ' + errorThrown);
alert('HTTP message body (jqXHR.responseText): ' + '\n' + jqXHR.responseText);
},
colNames: ["Id", "Item Type", "Item Code", "Unit", "Stock", "Batch No.", "Expiry Date", "Quantity Per Unit", "Price"],
colModel: [
{ name: "itemId", width: 35, align: "left", sorttype:"int", search: false},
{ name: "itemType", width: 100, align: "left", editable: true},
{ name: "itemCode", width: 120, align: "left", editable: true},
{ name: "unit", width: 70, align: "left", search: false, editable: true},
{ name: "availableQuantity", width: 55, align: "left", search: false, formatter: "number", editable: true},
{ name: "batchNumber", width: 80, align: "left", search: false, editable: true},
{ name: "expiryDate", width: 80, align: "left", search: false, sorttype: "date", editable: true, formatoptions: {srcformat:'d/m/Y', newformat:'d/m/Y'}},
{ name: "quantityPerUnit", width: 80, align: "left", search: false, formatter: "number", editable: true},
{ name: "price", width: 55, align: "left", search: false, formatter: "number", editable: true}
],
pager: "#itemListPager",
rowNum: 50,
rowList: [50, 100, 150, 200],
rownumbers: true,
rownumWidth: 25,
sortname: "id",
sortorder: "desc",
viewrecords: true,
height: '100%',
loadonce: true,
//gridview: true,
autoencode: true,
editurl: "${pageContext.request.contextPath}/billing/saveItem",
caption: "Item List",
ondblClickRow: function(rowId){}
}).navGrid('#itemListPager',{add:false,edit:false,del:true});
$("#itemList").jqGrid('filterToolbar', {autoSearch: true, stringResult: true, searchOnEnter: false, defaultSearch: 'cn'});
$("#itemList").jqGrid('gridResize', { minWidth: 450, minHeight: 150 });
var saveparameters = {
"successfunc" : null,
"url" : "${pageContext.request.contextPath}/billing/saveItem",
"extraparam" : {},
"aftersavefunc" : null,
"errorfunc": null,
"afterrestorefunc" : null,
"restoreAfterError" : true,
"mtype" : "POST"
};
var editparameters = {
"keys" : false,
"oneditfunc" : null,
"successfunc" : null,
"url" : "${pageContext.request.contextPath}/billing/editItem",
"extraparam" : {},
"aftersavefunc" : null,
"errorfunc": null,
"afterrestorefunc" : null,
"restoreAfterError" : true,
"mtype" : "POST"
};
var parameters = {
edit: true,
editicon: "ui-icon-pencil",
add: true,
addicon:"ui-icon-plus",
save: true,
saveicon:"ui-icon-disk",
cancel: true,
cancelicon:"ui-icon-cancel",
addParams : saveparameters,
editParams : editparameters
};
$("#itemList").jqGrid('inlineNav',"#itemListPager", parameters);
});
});
</script>
The sample json dada is as,
[
{"itemDetailId":1,"itemId":1,"itemType":"Medicine","itemCode":"Aler-Dryl","itemDesc":"Aler-Dryl","batchNumber":"batch1","expiryDate":"18/02/2017","unit":"tablet","subUnit":"tablet","availableQuantity":120.0,"quantityPerUnit":60.0,"price":122.0},
{"itemDetailId":2,"itemId":2,"itemType":"Medicine","itemCode":"Benadryl","itemDesc":"Benadryl","batchNumber":"batch1","expiryDate":"18/02/2017","unit":"ml","subUnit":"ml","availableQuantity":60.0,"quantityPerUnit":120.0,"price":90.0}
]
Now the url specified in editparameters and saveparameters is getting invoked on editing and adding a row respectively.
Please suggest if above approach is a good one. Also how can we set a request header before edit or save data is posted to server. And i can not find anything like deleteparameters similar to editparameters and saveparameters so that i can use delete specific parameters.
UPDATE 2:-
I could successfully set a request header before server side code is invoked on add/edit row using following code,
$.ajaxSetup({
beforeSend: function (jqXHR, settings) {
jqXHR.setRequestHeader("X-CSRF-TOKEN", $("input[name='_csrf']").val());
}});
UPDATE 3:-
Cleaned up code as per Oleg's suggestions as below. But in the strict mode i am getting JS error now - "Uncaught ReferenceError: saveparameters is not defined"
<script type="text/javascript">
$(document).ready(function () {
"use strict";
var dataGrid = $('#itemList');
var firstClick = true;
$('#action').click(function () {
if (!firstClick) {
$("#itemList").setGridParam({datatype:'json'}).trigger("reloadGrid");
}
firstClick = false;
$("#itemList").jqGrid({
url: "${pageContext.request.contextPath}/billing/medicines",
datatype: "json",
mtype: "POST",
autowidth: true,
loadBeforeSend: function(jqXHR) {
jqXHR.setRequestHeader("X-CSRF-TOKEN", $("input[name='_csrf']").val());
},
colNames: ["Id", "Item Type", "Item Code", "Unit", "Stock", "Batch No.", "Expiry Date", "Quantity Per Unit", "Price"],
colModel: [
{ name: "itemId", width: 35, align: "left", sorttype:"int", search: false, editable: false, key: true},
{ name: "itemType", width: 100, align: "left"},
{ name: "itemCode", width: 120, align: "left"},
{ name: "unit", width: 70, align: "left", search: false},
{ name: "availableQuantity", width: 55, align: "left", search: false, formatter: "number",},
{ name: "batchNumber", width: 80, align: "left", search: false},
{ name: "expiryDate", width: 80, align: "left", search: false, sorttype: "date", formatoptions: {srcformat:'d/m/Y', newformat:'d/m/Y'}},
{ name: "quantityPerUnit", width: 80, align: "left", search: false, formatter: "number"},
{ name: "price", width: 55, align: "left", search: false, formatter: "number"}
],
cmTemplate: {editable: true},
pager: true,
rowNum: 50,
rowList: [50, 100, 150, 200],
rownumbers: true,
rownumWidth: 25,
sortname: "itemType",
sortorder: "asc",
forceClientSorting: true,
viewrecords: true,
height: '100%',
loadonce: true,
//gridview: true,
autoencode: true,
editurl: "${pageContext.request.contextPath}/billing/saveItem",
caption: "Item List"
//ajaxRowOptions: { beforeSend: myTokenSetting }, loadBeforeSend: myTokenSetting where var myTokenSetting = function(jqXHR) { jqXHR.setRequestHeader("X-CSRF-TOKEN", $("input[name='_csrf']").val()); }
}).navGrid({add:false,edit:false,del:true});
$("#itemList").jqGrid('filterToolbar', {autoSearch: true, stringResult: true, searchOnEnter: false, defaultSearch: 'cn'});
$("#itemList").jqGrid('gridResize', { minWidth: 450, minHeight: 150 });
var saveparameters = {
"successfunc" : null,
"url" : "${pageContext.request.contextPath}/billing/saveItem",
"extraparam" : {},
"aftersavefunc" : null,
"errorfunc": null,
"afterrestorefunc" : null,
"restoreAfterError" : true,
"mtype" : "POST"
};
var editparameters = {
"keys" : false,
"oneditfunc" : null,
"successfunc" : null,
"url" : "${pageContext.request.contextPath}/billing/editItem",
"extraparam" : {},
"aftersavefunc" : null,
"errorfunc": null,
"afterrestorefunc" : null,
"restoreAfterError" : true,
"mtype" : "POST"
};
var parameters = {
edit: true,
editicon: "ui-icon-pencil",
add: true,
addicon:"ui-icon-plus",
save: true,
saveicon:"ui-icon-disk",
cancel: true,
cancelicon:"ui-icon-cancel",
addParams : saveparameters,
editParams : editparameters
};
$("#itemList").jqGrid('inlineNav',parameters);
$.ajaxSetup({
beforeSend: function (jqXHR, settings) {
alert('Before Row Send');
jqXHR.setRequestHeader("X-CSRF-TOKEN", $("input[name='_csrf']").val());
}});
});
});
</script>
You should examine the options of inlineNav to find out that you use absolutely wrong options:
jQuery("#grid_id").jqGrid('inlineNav', pagerid, parameters);
where parameters have the form
{
edit: true,
editicon: "ui-icon-pencil",
add: true,
addicon: "ui-icon-plus",
save: true,
saveicon: "ui-icon-disk",
cancel: true,
cancelicon: "ui-icon-cancel",
addParams: {useFormatter : false},
editParams: {}
}
You use the options of another method navGrid
jQuery("#grid_id").jqGrid('navGrid', '#gridpager', {parameters},
prmEdit, prmAdd, prmDel, prmSearch, prmView);
which allows to use form editing.
You wrote that you want to use both formater: "actions" andinlineNav. Thus you would have to provide some options of inline editing twice. I would recommend you to read [the wiki article](https://github.com/free-jqgrid/jqGrid/wiki/New-style-of-usage-options-of-internal-methods). It describes the problems with the usage of form editing usingformatter: "actions"andnavGridtogether. The usage of inline editing have very close problems. You will have to provideaddParamsandeditParamsproperties ofinlineNavand the corresponding options offormatter: "actions"` (see here). To make the code more readable and simple free jqGrid provides another form of editing options.
You can specify all inline editing options inside of inlineEditing option of jqGrid, additional specific options of inlineNav method (if required) in navOptions or in inlineNavOptions, the options of Delete operation in formDeleting and so on. Moreover reloadGrid have the option fromServer: true to restore the original value of datatype ("json", "jsonp", "xml", ...) which you used. You can use reloadGridOptions: { fromServer: true } option of form editing or formDeleting to force reloading from the server.
Moreover your existing code contains many very suspected parts with _id and EmpId. I would strictly recommend you to include the example of format of input JSON data which you use to fill the grid. If you want to use EmpId as the name of rowid why you use _id instead? The code fragment like
EmpId: function () {
var sel_id = $('#itemList').jqGrid('getGridParam', 'selrow');
var value = $('#itemList').jqGrid('getCell', sel_id, '_id');
return value;
}
shows that the current rowid seems be wrong and _id column contains correct information which you need as rowid under the name EmpId.
You can for example use prmNames: { id: "EmpId"} and to add key: true to the column _id. The property key: true in the column _id will inform jqGrid to use the value from the column _id as the rowid and prmNames: { id: "EmpId"} will rename default id property used in Edit and Delete to EmpId. Thus jqGrid will automatically send EmpId parameter with the value from _id column during Delete and Edit operations to the server.
Probably you can remove unneeded column _id from the grid too (at least if you hold the column hidden), but I need to see input data of jqGrid to say you exact options of jqGrid which you can use.
I'm sure that you can essentially reduce your existing code and make it more readable using free jqGrid options, but you have to review your existing code carefully. I suggest you to start with the usage of correct rowid and elimination of all hidden columns which you use. Free jqGrid provides additionalProperties feature which structure is very close to the structure of colModel, but the corresponding properties of input data will be saved in the local data only and not placed in DOM of the table. I can explain all more clear if you would post your existing colModel, jsonReader and example of JSON response returned from the server (1-2 rows of data with dummy data would be enough).

Define custom sorting on free jqgrid

I have a column called InterestedValue, where I would like to allow sorting, by the label of the dropdown.
I found similar questions and I implemented the recommended solution, but it does not work.
Essentially, nothing happens, the applications behaves exactly like before we added the custom sorttype. Even adding alerts in it, nothing happens, get no errors, or anything.
{
name: 'InterestedValue', editable: true, sortable: true, formatter: 'select', width: 110, search: false, edittype: 'select',
editoptions: {
value: InterestedStatusList,
},
sorttype: function (cellvalue)
{
return InterestedStatusList[cellvalue];
}
}
I added the loadonce: true as suggested, and now I can sort the data correctly, but when I have more records than the ones shown in the first screen, I cannot visualize them.
My code is:
$(gridId).jqGrid(//'setGroupHeaders',
{
url: actionMethod,
shrinkToFit: false,
datatype: 'json',
mtype: 'GET',
loadonce: true,
//sortable: true,
colNames: [MyColumns],
colModel: [
{MyModel }
],
pager: jQuery(pagerId), //jQuery('#pager'),
rowNum: 10,
rowTotal: 2000,
rowList: [10, 20, 30, 40],
height: '100%',
//width:700,
viewrecords: true,
caption: caption,
emptyrecords: 'No records to display',
jsonReader: {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
Id: "0"
},
//autowidth: true,
multiselect: false,
gridview: true,
editurl: '/InvestorList/Edit',
onSelectRow: function (id) {
if (id) {
$(gridId).jqGrid("editRow", id, true, '', '', '', '', reload)
//ORIGINAL CODE: $(gridId).editRow(id, true,'', '', '', '', reload);
lastSelectedId = id;
}
},
serializeRowData: function (postdata) {
//var response = JSON.stringify(postdata);
var s = '';//'<select>';
$(postdata).each(function (index, data) {
//s += '<option value="' + index + '">' + data + '</option>';
$.each(data, function (k, v) {
if (k == "InterestedValue")
s += v;//'<option value="' + k + '">' + v + '</option>';
});
});
//alert("s=" + s);
if (s.indexOf("100010002") != -1) { //"2_1") {
if (confirm('Are you sure you want to deactivate this record? ')) {
// do things if OK
return postdata;
}
else
return false;
}
return postdata;
},
Essentially I see the first ten records, and I have no way of accessing the remaining ones.
How can I fix this?

Unable to sort jqGrid column with sorttype function

Trying to sort a grid with custom sort. I am building jqgrid with dynamic columns and data. Everything works well except sorting of one of the column. I am using javax.json to build the json and I am using jqgrid 4.7.0. Here is the grid code:
var resultsGrid = $("#resultsGrid");
var url = "grid/GridDataController?action=runSearch&searchText="+getSearchText()+"&_ts"+$.now();
var csvUrl = "grid/GridDataController?action=downloadCsv&_ts"+$.now();
var gridPagerId="#resultsPager";
var drawSearchResultsGrid = function(colNames,colModel,data) {
resultsGrid.disableSelection(); //disales highlioghting cells outside selection like ghosting.
resultsGrid.jqGrid({
url: url,
datatype: 'jsonstring',
loadonce: true,
mtype: "GET",
height: 300,
width: 700,
colNames: colNames,
colModel: colModel,
datastr : data,
rowNum: 100000,
sortname: "invid",
sortorder: "asc",
rownumbers: true,
viewrecords: true,
pager: gridPagerId,
pginput : false,
pgbuttons : false,
viewrecords : false,
gridview: true,
autoencode: true,
onSelectRow : function(id) {
logMessage("row selected ["+id+"]");
},
loadComplete: function(data) {
logMessage("load completed");
},
ondblClickRow : function(rowid) {
logMessage("Double clicked");
$(escapeColon("#contentForm:viewPropertiesButton")).click();
}
});
// Set navigator with search enabled.
resultsGrid.jqGrid('navGrid',gridPagerId,{add:false,edit:false,del:false,search:false,refresh:false});
// add custom button to export the data to excel
resultsGrid.jqGrid('navButtonAdd',gridPagerId,{
caption:"Export",
onClickButton : function () {
resultsGrid.jqGrid('excelExport',{"url":csvUrl});
}
});
}; //end drawResultGrid function
//get grid config...
$.ajax({
type: "GET",
url: url,
data: "",
dataType: "json",
success: function(response)
{
if (response.result == "0")
{
logMessage("Drawing results grid...");
drawSearchResultsGrid(response.colNames,response.colModel,response.data);
resizeGrid();
logMessage("Results grid drawing done.");
}
else
{
logMessage("Error : " + response.message);
alert(response.message);
}
},
error: function(x, e)
{
alert(x.readyState + " "+ x.status +" "+ e.msg);
}
});
Here is my dynamic colModel looks like:
{
"result":"0",
"message":"",
"data":{
"records":18,
"total":1,
"page":"1",
"rows":[ ]
},
"colNames":[
"IP Address/Cidr",
"Name",
"IP Decimal",
"Cidr"
],
"colModel":[
{
"name":"adressCidr",
"width":50,
"sortable":true,
"hidden":false,
"sorttype":"function (cellValue,rowObject) { console.log('sorting by ['+rowObject.ipDecimal+']'); return parseInt(rowObject.ipDecimal,10);}"
},
{
"name":"name",
"width":50,
"sortable":true,
"hidden":false
},
{
"name":"ipDecimal",
"width":50,
"sortable":true,
"hidden":false,
"sorttype":"int"
},
{
"name":"cidr",
"width":0,
"sortable":false,
"hidden":true
}
]
}
ipDecimal is a hidden column but I am displaying it for testing purpose. Requirement is first column 'addressCidr' is a string column but i want to sort it using hidden ipDecimal column. The function neither does show console.log message nor does any sorting properly. However, If i sort by ipDecimal with sorttype as 'int' by clicking on its header, it works fine. Only thing i can think of is the double quote around the sorttype function itself. Please let me know if you see any other issue here, or what is the best way to solve this case. Here is snippet where I build json function:
private JsonObjectBuilder createColumn(JsonBuilderFactory factory,
String name,int width,boolean sortable,boolean hidden,boolean sorttype)
{
JsonObjectBuilder column =this.createColumn(factory, name, width, sortable, hidden);
StringBuilder fnBuilder = new StringBuilder("");
//this is not generic but can easily be made one :(
fnBuilder.append("function (cellValue,rowObject) {");
fnBuilder.append(" console.log('sorting by ['+rowObject.ipDecimal+']');");
fnBuilder.append(" return parseInt(rowObject.ipDecimal,10);");
fnBuilder.append("}");
column.add("sorttype", fnBuilder.toString()); // this works, not sure why above function does not work :(
return column;
}
private JsonObjectBuilder createColumn(JsonBuilderFactory factory,
String name,int width,boolean sortable,boolean hidden)
{
JsonObjectBuilder column;
column = factory.createObjectBuilder();
column.add("name", name);
column.add("width", width);
column.add("sortable", sortable);
column.add("hidden", hidden);
return column;
}
Data I used for testing is:
IpAddressCidr ipDecimal
5.1.0.0/24--83951616
5.1.1.0/24--83951872
5.1.2.0/24--83952128
5.1.3.0/24--83952384
5.1.4.0/24--83952640
5.3.0.0/24--84082688
5.9.2.0/24--84476416
6.0.0.0/24--100663296
6.0.1.0/24--100663552
6.0.2.0/24--100663808
6.0.3.0/24--100664064
6.0.4.0/24--100664320
6.0.5.0/24--100664576
7.1.0.0/24--117506048
7.1.1.0/24--117506304
7.1.2.0/24--117506560
7.1.3.0/24--117506816
198.186.198.0/24--3334129152
But here is that I see
Ip 198.186.198.0 should have appeared at the top as it has highest ipDecimal, but it gets pushed to the bottom.
To add more test information. If I remove enclosed double quotes, sort works fine, but not with it.
Following works:
{ name: "adressCidr", width:50, sortable: true,
sorttype: function (cellValue,rowObject) { console.log('sorting by ['+rowObject.ipDecimal+']');return parseInt(rowObject.ipDecimal,10);}},
Following does not:
{ name: "adressCidr", width:50, sortable: true,
sorttype: "function (cellValue,rowObject) { console.log('sorting by ['+rowObject.ipDecimal+']');return parseInt(rowObject.ipDecimal,10);}"},
The reason of your problem is the usage of sorttype which you defines as string instead of function:
{
"name":"adressCidr",
"width":50,
"sortable":true,
"hidden":false,
"sorttype":"function (cellValue,rowObject) { console.log('sorting by ['+rowObject.ipDecimal+']'); return parseInt(rowObject.ipDecimal,10);}"
}
You use jqGrid 4.7 which contains new feature which I suggested (see here). So you can include the code like
$.extend($.jgrid, {
cmTemplate: {
myIpAddress: {
sorttype: function (cellValue, rowObject) {
console.log('sorting by [' + rowObject.ipDecimal + ']');
return parseInt(rowObject.ipDecimal, 10);
},
width: 50
}
}
});
Now you can change the data returned from the server to
{
"name":"adressCidr",
"sortable":true,
"hidden":false,
"template":"myIpAddress"
}

Categories

Resources