How to convert a string to an array for the columns of a DataTable?

41 views Asked by At

I have the following code that works perfectly, but I would like to replace the array of columns with a variable. I have created in php the string:

$datos = "[{data: 'id'},{data: 'nombre'},{data: 'telefono'},{data: 'email'},{data: 'status'}]";

and in Javascript I try to associate it with the DataTable:

<script>
$( document ).ready(function() {    
    var result = JSON.parse('<?php echo $result ?>'); 
    var datos = '<?php echo $datos ?>'; 
    //var datos = JSON.stringify('<?php echo $datos ?>');
    //var datos = JSON.parse('<?php echo $datos ?>');   
    
    var table = $('#registros').DataTable({
        data: result,
        columns: datos
        /*columns: [{data: 'id'},{data: 'nombre'},{data: 'telefono'},{data: 'email'},{data: 'status'}]*/
    });

});
</script>

but that doesn't work, the conversion of the string "datos" is not done well. I have tried with:

var datos = JSON.stringify('<?php echo $datos ?>');

and with

var datos = JSON.parse('<?php echo $datos ?>'); 

but I don't get it. Can anybody help me? Thanks in advance.

1

There are 1 answers

1
Parth Goswami On

I guess what you are doing wrong over here is, columns array look out for title paramter along with data to render column header. So can you try ahead with this

$datos = [
        { "data": "id", "title": "id" },
        { "data": "number", "title": "nombre" }
    ];

where data param is key of your result response & title is column header.