I'm trying to use datatables with a set number of columns and an array of objects I get from jQuery ajax.
I get the error:
datatables warning (table id = myId requested unknown parameter 0 from the data source for row 0
Searching the internet has shown me that it's probable I have a different number of column headers and column data in my message_json array;
I have 21 columns set up in my data table initialization:
var construct_messages_table = function(message_json){
var oTable = $('#tableId').dataTable( {
"sPaginationType": "full_numbers",
"bProcessing": true,
"bDeferRender": true,
"aaData": message_json,
"aoColumns": [
{ "sTitle": "coloumn1"},
{ "sTitle": "coloumn2"},
{ "sTitle": "coloumn3"},
{ "sTitle": "coloumn4"},
{ "sTitle": "coloumn5"},
{ "sTitle": "coloumn6"},
{ "sTitle": "coloumn7"},
{ "sTitle": "coloumn8"},
{ "sTitle": "coloumn9"},
{ "sTitle": "coloumn10"},
{ "sTitle": "coloumn11"},
{ "sTitle": "coloumn12"},
{ "sTitle": "coloumn13"},
{ "sTitle": "coloumn14"},
{ "sTitle": "coloumn15"},
{ "sTitle": "coloumn16"},
{ "sTitle": "coloumn17"},
{ "sTitle": "coloumn18"},
{ "sTitle": "coloumn19"},
{ "sTitle": "coloumn20"},
{ "sTitle": "coloumn21"}
]
} );
};
And
for (var i = 1; i < message_json.length; i++){
console.log(Object.keys(message_json[i]).length);
}
shows all objects have a length of 21. What could be wrong here?
EDIT:
I've removed nulls as that might be the problem, but still no help.
for (var i = 0; i < message_json.length; i++){
for (var o in message_json[i]){
if (message_json[i][o] == null){
message_json[i][o] = "";
}
}
}
EDIT:
message_json is in this format
[
{type: "int",
id: "111",
name: "co",
description: "",
is_bool: "0",
keyword: "<tag name="various-xml">fields</xml>",
message: "hello",
temp: "world",
settings: "",
priority: "100",
enabled: "0",
secure: "1",
var1: "post",
var1_desc: "some desc↵",
var1_query: "<DATA>blah</DATA>",
prop: "1",
prop_name: "Draft",
transaction: "1",
users: "0",
table_name: "abc"},
{type: "int",
id: "111",
name: "co",
description: "",
is_bool: "0",
keyword: "<tag name="various-xml">fields</xml>",
message: "hello",
temp: "world",
settings: "",
priority: "100",
enabled: "0",
secure: "1",
var1: "post",
var1_desc: "some desc↵",
var1_query: "<DATA>blah</DATA>",
prop: "1",
prop_name: "Draft",
transaction: "1",
users: "0",
table_name: "abc"}];
But with lots more elements of course. And not just a duplicates.
Well the number of elements must be the same as the columns otherwise Datatables will look for a value not included in the data.
If you want to use a structure like the one in:
[
{type: "int",
id: "111",
name: "co",
description: "",
is_bool: "0",
keyword: "<tag name="various-xml">fields</xml>",
message: "hello",
temp: "world",
settings: "",
priority: "100",
enabled: "0",
secure: "1",
var1: "post",
var1_desc: "some desc↵",
var1_query: "<DATA>blah</DATA>",
prop: "1",
prop_name: "Draft",
transaction: "1",
users: "0",
table_name: "abc"},
{type: "int",
id: "111",
name: "co",
description: "",
is_bool: "0",
keyword: "<tag name="various-xml">fields</xml>",
message: "hello",
temp: "world",
settings: "",
priority: "100",
enabled: "0",
secure: "1",
var1: "post",
var1_desc: "some desc↵",
var1_query: "<DATA>blah</DATA>",
prop: "1",
prop_name: "Draft",
transaction: "1",
users: "0",
table_name: "abc"}];
It will be better to use "sAjaxSource" on your dataTable
When you add the aaData to your datatables normally they provide an array of arrays:
Example:
Fiddle
If your want to use a key:value JSON object you will need to add the mData property to your aoColumms config like this:
var oTable = $('#tableId').dataTable( {
"sPaginationType": "full_numbers",
"bProcessing": true,
"bDeferRender": true,
"aaData": message_json,
"aoColumns": [
{ "sTitle": "coloumn1","mData":"type"},
{ "sTitle": "coloumn2","mData":"id"},
{ "sTitle": "coloumn3","mData":"name"},
{ "sTitle": "coloumn4","mData":"description"},
{ "sTitle": "coloumn5","mData":"is_bool"},...
This will tell datatables where to find the value for that column.
Related
I am trying to display data and view/edit/delete buttons using datatables.
I am getting user data and permission using two objects like this:
]
{
"data": [
{
"userid": "1",
"username": "John",
"email": "john#gmail.com",
"userrole": "SYSTEM VENDOR",
"isactive": "Y",
"activationstat": "deactivate",
"activationmsg": "Deactivate"
}
],
"perm":
{
"read": "y",
"edit": "y",
"delete": "n"
}
}
The button needs to be rendered for each row. Datatables code is as:
$('#dt-user').DataTable({
dom: 'lBfrtip',
buttons: [
{
extend: 'copyHtml5',
exportOptions: {
columns: ':visible'
}
},
{
extend: 'csvHtml5',
exportOptions: {
columns: ':visible'
}
},
{
extend: 'excelHtml5',
exportOptions: {
columns: ':visible'
}
},
{
extend: 'pdfHtml5',
exportOptions: {
columns: ':visible'
}
},
{
extend: 'print',
exportOptions: {
columns: ':visible'
}
},
'colvis'
],
ajax: baseURL + 'user/list-user-aj',
columns: [
{
"data": "id",
render: function (data, type, row, meta) {
return meta.row + meta.settings._iDisplayStart + 1;
}
},
{ data: 'username' },
{ data: 'email' },
{ data: 'userrole' },
{ data: 'isactive' }
],
responsive: {
details: false
}
});
How can I access the "perm" JSON object for checking its values for displaying buttons for edit, delete, print etc?
Short answer: You will not be able to get "perm" object within datatables initialization code. Datatables initialization code only works with "data" array from JSON.
However, here are two possible solutions to your situation:
Option 1:
If the "perm" object is going to be common for all elements (users) in the "data" array in JSON, like follows:
{
"data": [
{
"userid": "1",
"username": "John",
"email": "john#gmail.com",
"userrole": "SYSTEM VENDOR",
"isactive": "Y",
"activationstat": "deactivate",
"activationmsg": "Deactivate"
},
{
"userid": "2",
"username": "John2",
"email": "john2#gmail.com",
"userrole": "SYSTEM VENDOR2",
"isactive": "Y",
"activationstat": "deactivate",
"activationmsg": "Deactivate"
}
<!-- and maybe some more objects-->
],
"perm":
{
"read": "y",
"edit": "y",
"delete": "n"
}
}
then you can access the perm object like below: (and that would be outside of Datatables definition)
var permissions;
userDatatable.on('xhr', function () {
var json = userDatatable.ajax.json();
var permissions = json.perm;
});
where userDatatable will be the global javascript variable when you initialize Datatables like below:
var userDatatable = $('#dt-user').DataTable({ //......and all your code
Then inside your columns definition, you can access perm object and render buttons like this:
columns:[
{
data:null,
"render": function(data, type, row, meta){
if(perm.delete === 'y'){
return "<button class='deleteButton'> Delete </button>";
}
}
}
]
Make sure javascript variable "permissions" is global and visible to your Datatables initialization code. This will get you the Delete button, but you will have to write additional Javascript/JQuery code to trigger the Datatables Editor's AJAX call to delete the row; both at backend and from the grid.
Option 2: You could modify your server-side code to return JSON such that it will have permissions object within each element of the "data" array:
{
"data": [
{
"userid": "1",
"username": "John",
"email": "john#gmail.com",
"userrole": "SYSTEM VENDOR",
"isactive": "Y",
"activationstat": "deactivate",
"activationmsg": "Deactivate",
"perm":
{
"read": "y",
"edit": "y",
"delete": "n"
}
},
{
"userid": "2",
"username": "John2",
"email": "john2#gmail.com",
"userrole": "SYSTEM VENDOR2",
"isactive": "Y",
"activationstat": "deactivate",
"activationmsg": "Deactivate",
"perm":
{
"read": "y",
"edit": "y",
"delete": "n"
}
}
<!-- and maybe some more objects-->
]
}
With this second option, you could access perm object within the "render" function using "row.perm.delete" property.
Hope this help!
I have dojo treeGrid that works fine. It shows projects with cost categorized by year. Also it shows totals. But when I try to filter it by one of column it mess up the grid (breaks categories and filter records improperly). Do I use grid.filter properly? I need to keep categorized structure but remove/filter certain records. Or should I refresh jsonStore somehow instead?
//HTML
<div id="treeGrid"></div>
<a href="javascript:void(0)">
<span id='button1'>Filter</span>
</a>
//JavaScript
var layout = [
{ cells: [
[ {field: "year", name: "Year"},
{field: "childItems",
children: [ { field: "status", name: "Status"},
{ field: "programname", name: "Program Name"},
{ field: "programcost", name: "Program Cost"}
],
aggregate: "sum"
}
]] } ]
var jsonStore = new dojo.data.ItemFileWriteStore({ url: "<........>"});
var grid = new dojox.grid.TreeGrid({
structure: layout,
store: jsonStore,
query: {type: 'year'},
queryOptions: {deep: true},
rowSelector: true,
openAtLevels: [false],
autoWidth: true,
autoHeight: true
},
dojo.byId("treeGrid"));
/* attach an event handler */
on(dom.byId("button1"),'click',
function(e){
grid.filter({status: "Approved"});
}
);
grid.startup();
dojo.connect(window, "onresize", grid, "resize");
/* sample data ======================================================
{
"identifier": "id",
"label": "name",
"items": [
{
"id": "2018",
"type": "year",
"year": "2018",
"childItems": [
{
"status": "Approved",
"programname": "Program 1",
"programcost": 100
},
{
"status": "Pending",
"programname": "Program 2",
"programcost": 200
}
]
},
{
"id": "2016",
"type": "year",
"year": "2016",
"childItems": [
{
"status": "Pending",
"programname": "Program 3",
"programcost": 300
}
]
}
]
}
*/
I used kendo grid to load data, I have a problem. aggregate sum not working correct with json data below,Total value only get last row cell value. If i change another json data it working.
var ds = [
{
"SubName": "To PN 01-001", "SubID": "1",
"Partner": "93",
"INFDivName": "Phuong Nam-01",
"Vigor2910wifi": "28"
},
{
"SubName": "To PN 01-002",
"SubID": "2", "Partner": "93",
"INFDivName": "Phuong Nam-01",
"Vigor2910wifi": "3"
},
{
"SubName": "To PN 01-010",
"SubID": "10", "Partner": "93",
"INFDivName": "Phuong Nam-01",
"Vigor2910wifi": "5"
}
];
var cls = [
new ExtColumn("Vigor2910wifi", "Cap", 300, null, false,null, null, "total #=sum#")
];
var dataSource = new kendo.data.DataSource({
data: ds,
pageSize: 20,
aggregate: [new ExtAggregate("Vigor2910wifi", "sum")],
})
var kendoGrid = $("#gridEQReportDebtBySub").kendoGrid({
dataSource: dataSource,
sortable: true,
resizable: true,
reorderable: true,
pageable: true,
columnMenu: true,
columns: cls
})
I found problem, I change
"Vigor2910wifi": "3"
to
"Vigor2910wifi": 3
This worked.
I am using jquery DataTables to bind my JSON data to the Table, however when I specify the JSON object to the 'aaData' option of the DataTable, it throws me this error:
"DataTables warning (table id = 'tblReceipt'): Requested unknown parameter '1' from the data source for row 0"
My JSON object looks like this:
var r = [
{ "Vid": "1", "Receiptno": "AFL123", "Type": "3", "Branch": "AFL", "Date": "23/11/2013" },
{ "Vid": "2", "Receiptno": "AFL124", "Type": "4", "Branch": "AFL", "Date": "24/11/2013" },
{ "Vid": "3", "Receiptno": "AFL125", "Type": "6", "Branch": "AFL", "Date": "25/11/2013" },
];
I am passing it to DataTables like this:
$("#tblReceipt").dataTable({
"aaData": JSON.stringify(r),
"bJQueryUI": true,
"bDestroy": true,
"iDisplayLength": 50,
"bProcessing": true,
"aaSorting": [[0, 'desc']],
"aoColumns": [
{ "mData": "Vid" },
{ "mData": "Receiptno" },
{ "mData": "Type" },
{ "mData": "Branch" },
{ "mData": "Date" },
],
"oLanguage": {
"sProcessing": "Fetching Data, Please wait..."
},
});
Any help would be greatly appreciated!
Just replace "aaData": JSON.stringify(r), with "aaData": r,.
Working demo: http://jsfiddle.net/qMPzh/1/
I am using treegrid of jqgrid, in which i want multiselect which is not possible , so i explicitely put a checkbox column. Now I want to know how to iterate each row of tree grid and access particular cell of that row, so that I can do specific action on it. Thank in advance.
The simplest way to implement your requirements seems me to include additional column in the tree grid which has the checkbox:
You have not posted the code of the grid which you are using. It is even not clear if you are using local tree grid or a remote one. In the following example I am showing how to implement the checkbox from the "Enabled" column in case of local grid. So you can have the following results:
The corresponding demo you will find here.
The HTML code is:
<fieldset style="float:left">
<input id="getSelected" type="button" value="Get Selected"/>
</fieldset>
<fieldset style="clear:both; float:left">
<legend>Seleceted Ids</legend>
<p id="ids"></p>
</fieldset>
<fieldset style="clear:both; float:left">
<legend>Selected Names</legend>
<p id="names"></p>
</fieldset>
<div style="clear:left">
<table id="treegrid"><tr><td/></tr></table>
</div>
and the JavaScript code:
$(function () {
'use strict';
var mydata = [
{ id: "1", name: "Cash", num: "100", debit: "400.00", credit: "250.00", balance: "150.00", enbl: "1",
level: "0", parent: "null", isLeaf: false, expanded: false },
{ id: "2", name: "Cash 1", num: "1", debit: "300.00", credit: "200.00", balance: "100.00", enbl: "0",
level: "1", parent: "1", isLeaf: false, expanded: false, loaded: true },
{ id: "3", name: "Sub Cash 1", num: "1", debit: "300.00", credit: "200.00", balance: "100.00", enbl: "1",
level: "2", parent: "2", isLeaf: true, expanded: false },
{ id: "4", name: "Cash 2", num: "2", debit: "100.00", credit: "50.00", balance: "50.00", enbl: "0",
level: "1", parent: "1", isLeaf: true, expanded: false },
{ id: "5", name: "Bank\'s", num: "200", debit: "1500.00", redit: "1000.00", balance: "500.00", enbl: "1",
level: "0", parent: "null", isLeaf: false, expanded: true, loaded: true },
{ id: "6", name: "Bank 1", num: "1", debit: "500.00", credit: "0.00", balance: "500.00", enbl: "0",
level: "1", parent: "5", isLeaf: true, expanded: false },
{ id: "7", name: "Bank 2", num: "2", debit: "1000.00", credit: "1000.00", balance: "0.00", enbl: "1",
level: "1", parent: "5", isLeaf: true, expanded: false },
{ id: "8", name: "Fixed asset", num: "300", debit: "0.00", credit: "1000.00", balance: "-1000.00", enbl: "0",
level: "0", parent: "null", isLeaf: true, expanded: false }],
grid = $("#treegrid"),
getColumnIndexByName = function (columnName) {
var cm = grid.jqGrid('getGridParam', 'colModel'), i, l = cm.length;
for (i = 0; i < l; i++) {
if (cm[i].name === columnName) {
return i; // return the index
}
}
return -1;
},
iCol;
grid.jqGrid({
datatype: "local",
colNames: ["id", "Account", "Acc Num", "Debit", "Credit", "Balance", "Enabled"],
colModel: [
{name: 'id', index: 'id', width: 1, hidden: true, key: true},
{name: 'name', index: 'name', width: 180},
{name: 'num', index: 'acc_num', width: 80, align: "center"},
{name: 'debit', index: 'debit', width: 80, align: "right"},
{name: 'credit', index: 'credit', width: 80, align: "right"},
{name: 'balance', index: 'balance', width: 80, align: "right"},
{name: 'enbl', index: 'enbl', width: 60, align: 'center',
formatter: 'checkbox', editoptions: {value: '1:0'},
formatoptions: {disabled: false}}
],
height: '100%',
rowNum: 10000,
sortname: 'id',
treeGrid: true,
loadonce: true,
treeGridModel: 'adjacency',
treedatatype: 'local',
ExpandColumn: 'name',
caption: 'Demonstrate how to use Tree Grid for the Adjacency Set Model'
});
// we have to use addJSONData to load the data
grid[0].addJSONData({
total: 1,
page: 1,
records: mydata.length,
rows: mydata
});
iCol = getColumnIndexByName('enbl');
// nth-child need 1-based index so we use (iCol+1) below
$("tbody>tr.jqgrow>td:nth-child(" + (iCol + 1) + ")>input", grid[0]).change(function (e) {
var isChecked = $(this).attr("checked"), rowid, dataIndex,
tr = $(e.target, grid[0].rows).closest("tr.jqgrow");
if (tr.length > 0) {
rowid = tr[0].id;
dataIndex = grid[0].p._index[rowid];
if (typeof dataIndex !== "undefined" && dataIndex >= 0) {
grid[0].p.data[dataIndex].enbl = isChecked ? "1" : "0";
}
}
e.preventDefault();
});
$("#getSelected").click(function () {
var ids = [], names = [], i, data = grid[0].p.data, l = data.length, dataItem;
for (i = 0; i < l; i++) {
dataItem = data[i];
if (dataItem.enbl === "1") {
ids.push(dataItem.id);
names.push(dataItem.name);
}
}
$("#ids").html(ids.join(", "));
$("#names").html(names.join(", "));
});
});
I think there not so difficult.
$("#YourTreegridContainerTag").find(":input[type=='checkbox']").each(function()
{
$(this).attr("cheked", "checked");
});
and for disablling:
$("#YourTreegridContainerTag").find(":input[type=='checkbox']").each(function()
{
$(this).removeAttr("cheked");
});