I am attempting to format a jQuery DataTable using json held in a database. I pass the json to the client in a hidden field in the response. I then try initialising the datatable with the following js:
function initDataTables(){
$('.datatable').each(function(i) {
// Look for a hidden field containing the json to use when initialising the datatable
var hiddenfieldkey = $(this).attr('id') + 'jsoninit'
var hiddenfield = $('#' + hiddenfieldkey);
if (hiddenfield.length > 0) {
// We have found some 'special' json formatting, so use it
var jsoninittext = $(hiddenfield).val();
alert(jsoninittext);
var json = $.parseJSON(jsoninittext);
alert('point two');
$(this).dataTable(json);
}
else {
// Standard datatable formatting
$(this).dataTable({
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"aLengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]]
});
}
});
initDataTableButtons();
}
This all works fine with the following json (I've just copied the sql that I use to fill the json init table in the db:
update query set jQueryDatatableJSONInit=
'{
"iDisplayLength": 25
,"bJQueryUI": true
,"sPaginationType": "full_numbers"
,"aLengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]]
,"aoColumnDefs": [
{ "bVisible": false, "aTargets": [ 0,3,4 ] }
,{ "sClass": "nowrap", "aTargets": [ 2 ] }
,{ "iDataSort": 0, "aTargets": [ 1 ] }
,{ "bSortable": false, "aTargets": [ 2 ] }
]
}'
where id ='336f7ea2-173a-4b8f-af30-e217d1e1c628'
However, a problem occurs when my json includes a function, as below (same as before, but includes an fnRender line containing a function):
update query set jQueryDatatableJSONInit=
'{
"iDisplayLength": 25
,"bJQueryUI": true
,"sPaginationType": "full_numbers"
,"aLengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]]
,"aoColumnDefs": [
{ "fnRender": function ( oObj ) { return oObj.aData[2] +'' ''+ oObj.aData[3]+'' ''+ oObj.aData[4];},"aTargets": [ 2 ]}
,{ "bVisible": false, "aTargets": [ 0,3,4 ] }
,{ "sClass": "nowrap", "aTargets": [ 2 ] }
,{ "iDataSort": 0, "aTargets": [ 1 ] }
,{ "bSortable": false, "aTargets": [ 2 ] }
]
}'
where id ='336f7ea2-173a-4b8f-af30-e217d1e1c628'
The following line fails (with an Invalid JSON error):
var json = $.parseJSON(jsoninittext);
and so the second alert (point two) never runs, so it doesn't get to the dataTable() function. It looks to me as if the function definition (containing braces) is causing the json to be invalid. Does anyone know how I could format the datatable initialisation json so that it can continue to contain a function definition as expected by jquery datatables, but that will still be valid json (is there sort sort of escape I could use)? Thanks very much.