I am new to jQuery and am attempting to use jQuery array as the datasource for the jQuery DataTable. The array is set-up exactly as I need, and I have verified such from using echo json_encode($data);
And this is the jQuery code I'm using....
<script type="text/javascript">
var information = <?php echo json_encode($data) ?>;
alert(information.toString());
$(document).ready(function () {
$('#my-table').dataTable({
data: information,
columns: [
{ title: 'Salesman' },
{ title: 'Office' },
{ title: 'Title' },
{ title: 'Salary' }
]
});
});
</script>
An example you have an array of variable in PHP :
And we want to output it as JSON format using json_encode function:
Will producing this:
Now as you embed this result inside javascript variable:
In client browser it will generated like this:
Above result is your javascript datasource. We use it with Datatables Data option. Some example in Datatables Javascript Sourced Data. It can be this can be arrays or objects.
When your PHP array got specific key index name, it will converted to same key in JSON object. So in Datatables this object key need to included inside columns.data option. You can use Datatables colums.title to set column name too.
See and run the demo snippet below:
Have you tried:
With
console.log
, you will see if your array is correctly parsed, and also usingJSON.parse
to pass your array fromPHP
toJS
is a better practice in my experience, less risky for syntax errors.