JSON question
JSON question
datatablesdeezteknet
Posts: 1Questions: 1Answers: 0
Hi,
I have the following JSON Output:
{
"COLUMNS": ["ID", "RECIPIENT", "POLICY_ID", "PDF_ENABLED", "SMIME_ENABLED", "PGP_ENABLED", "DIGITAL_SIGN"],
"DATA": [
[1639, "user1@domain.tld", 33, 2, 2, 2, 2],
[1046, "user2@domain.tld", 33, 1, 2, 2, 2],
[1277, "user3@domain.tld", 33, 1, 1, 2, 2],
[1051, "user4@domain.tld", 33, 1, 2, 2, 2],
[1676, "user5@domain.tld", 33, 2, 2, 2, 2],
[1615, "user6@domain.tld", 33, 2, 2, 2, 2],
[1055, "user7@domain.tld", 33, 2, 2, 2, 2],
[1056, "user8@domain.tld", 33, 2, 2, 2, 2],
[1254, "user9@domain.tld", 33, 2, 2, 2, 2],
[1264, "user10@domain.tld", 33, 1, 1, 2, 2],
[1642, "user11@domain.tld", 49, 2, 2, 2, 2]
]
}
How would I go about creating a table with that JSON data? Originally, I thought using the following would do it:
$(document).ready(function() {
$('#sortTable').DataTable( {
'processing': true,
'serverSide': true,
'ajax': './inc/get_int_recipients.cfm',
'columns': [
{ 'data': 'id' },
{ 'data': 'recipient' },
{ 'data': 'policy_id' },
{ 'data': 'pdf_enabled' },
{ 'data': 'smime_enabled' },
{ 'data': 'pgp_enabled' },
{ 'data': 'digital_sign' },
],
However, as soon as I insert the "columns" code in the script in an attempt to map the columns, I get the following error in the browser console:
Uncaught TypeError: Cannot read property 'mData' of undefined
at HTMLTableCellElement.<anonymous> (jquery.dataTables.min.js:104)
at Function.each (jquery-3.6.0.min.js:2)
at S.fn.init.each (jquery-3.6.0.min.js:2)
at HTMLTableElement.<anonymous> (jquery.dataTables.min.js:104)
at Function.each (jquery-3.6.0.min.js:2)
at S.fn.init.each (jquery-3.6.0.min.js:2)
at S.fn.init.u [as dataTable] (jquery.dataTables.min.js:97)
at S.fn.init.l.fn.DataTable (jquery.dataTables.min.js:185)
at HTMLDocument.<anonymous> (view_internal_recipients.cfm:125)
at e (jquery-3.6.0.min.js:2)
If, I don't use the "columns" code in the script, the table is blank, i.e. no data. What am I doing wrong?
Thanks
Answers
You enabled server side processing,
'serverSide': true,
, but your script isn't returning the required parameters. See the Server side processing protocol docs for more info. Unless you are going to have 10s of thousands of rows you probably won't need server side processing.You are probably getting this because Datatables doesn't know where the row data is located i your JSON. See the Ajax docs for more details. Basically, by default, Datatables looks for the data in the
data
object. But you haveDATA
. Its case sensitive. You can use theajax.dataSrc
option to point toDATA
or change the response to usedata
.Your rows are in an array structure not an object structure. The
columns.data
option is used for object data. See the `Data docs for more details. Usually its easier and the source code more readable if you use objects instead of arrays. See the Object data example and the array data example.Kevin