Reputation: 431
I am trying to handle the value of aoColumns from other php page. But then it is not coming properly, whereas if I use static value then its working. My code is like : in php page
$aoColumn = array("null","null","null","{bSortable: false}");
<input type="hidden" name="aoColumn" id="aoColumn" value="' . implode(",",$aoColumn) . '">
in js page
var aos = $('#aoColumn').val();
var ao = (aos)?aos.split(","):[];
$.each(ao,function(i){
});
and in dataTable declaration: "aoColumns":ao
But it is not working. Please let me know the issue. Thanks in advance.
UPDATE
I got to know that, in my case aoColumns
prints ["null", "null", "null", "{bSortable: false}"]
whereas it should be [null,null,null,Object{bSortable=false}]
. How to do it?
Upvotes: 2
Views: 2403
Reputation: 85538
This was a fun one :-) Taken your setup 1:1 (just 3 columns though) :
<?
$aoColumn = array("null", "{bSortable: false}", "null");
echo '<input type="hidden" name="aoColumn" id="aoColumn" value="' . implode(",",$aoColumn) . '">';
?>
JS
var ao = [];
var aos = $('#aoColumn').val().split(',');
for (var i=0;i<aos.length;i++) {
if (aos[i]=='null') {
//no need for processing
ao.push('{ null }');
} else {
//remove {, } and whitespace, return array splitted by :
var s = aos[i].replace('{','').replace('}','').replace(' ','').split(':');
//create object
var o = {};
//here you need to force a real boolean instead of "false"
o[s[0].toString()]=(s[1]=="false") ? false : true;
ao.push(o);
}
}
$('#table').dataTable({
"aoColumns": ao
});
Viola. Datatables parses ao
correct, the second column is not sortable.
Upvotes: 0
Reputation: 51
JSON.parse('[null, null, null, {"bSortable": false}]');
Modify your implode function so that your value="[null, null, null, {\"bSortable\": false}]"
and then run JSON.parse()
on the .val()
to get your settings object.
Upvotes: 0
Reputation: 437386
The way you pass $aoColumn
to your script is wrong. You should pass it as JSON instead -- and if the JSON is being transferred inside HTML, it needs to be properly HTML-encoded as well:
$aoColumn = array(null, null, null, array('bSortable' => false));
echo '<input ... value="' . htmlspecialchars(json_encode($aoColumn)).'">';
And turn it back into an object with $.parseJSON
:
var aoColumn = $.parseJSON($('#aoColumn').val());
However, I 'm not sure why you want to bother with the hidden field at all. You can pass the configuration to JavaScript directly:
<?php $aoColumn = array(null, null, null, array('bSortable' => false)); ?>
<!-- later on.... -->
<script>
var aoColumn = <?php echo json_encode($aoColumn); ?>;
</script>
Upvotes: 1