shreyash singh shreyash singh - 1 year ago 73
Ajax Question

PHP - JSON array to javascript datatable library

I am sending JSON array to my ajax response and trying to print a table with response data using datatable library , on my server side I am using this code

$products = array(
array('choc_cake', 'Chocolate Cake', 'scsdsf'),
array('carrot_cake', 'Carrot Cake', 'sdfds'),
array('cheese_cake', 'Cheese Cake', 'dsadas'),
array('banana_bread', 'Banana Bread', 'dasdas')
header('Content-Type: application/json');
echo json_encode( $products , JSON_PRETTY_PRINT);

which is producing json like
[ [x,y,z],[x,y,z],[x,y,z] ]
and I am passing the javascript ajax response string to datatable library code which is :

var saman = hr.responseText.trim();
$('#example').DataTable( {
data: saman,
columns: [
{ title: "Name" },
{ title: "Position" },
{ title: "Office" }
} );

but this code giving me this error

Answer Source

Do you want saman to be an array or a string?

If array, please use:

var saman = eval(hr.responseText.trim()); 

or it is just a string.

Remember: no matter what php outputs, it is only some text, not any live code so you have to use eval to parse it to an array.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download