Use PHP array into DataTable

Use PHP array into DataTable

KarkuroKarkuro Posts: 7Questions: 5Answers: 0

I already have a DataTable working in my project, retrieving data from a database table. Pretty simple. But now I want to do an other one.
I have an array that I json_encode and looks like this :

⋅⋅⋅
[
{
"message":"ztest",
"ticket":"cf7f3c1e-cba3-448e-9f38-4acac97e50a1",
"expname":"Besse",
"recname":"Dias",
"firstname":"Francois"
},
{
"message":"ztest",
"ticket":"cf7f3c1e-cba3-448e-9f38-4acac97e50a1",
"expname":"Besse",
"recname":"Arnold",
"firstname":"Jean"
},
⋅⋅⋅

I'd like to put that into a DataTable.

⋅⋅⋅
$(document).ready(function() {
$('#datatable').DataTable( {
"ajax": "<?php echo $array"; ?>",
"columns": [
{ "data": "message" },
{ "data": "ticket" },
{ "data": "expname" },
{ "data": "recname" },
{ "data": "firstname" }
]
} );
} );
⋅⋅⋅

But that doesn't work. I really don't know how to do right now.

Answers

  • NeiculNeicul Posts: 6Questions: 3Answers: 0

    Datatables needs a format like this:

    {
    "data":[
    {
    "message":"This is a message",
    "ticket":"This is a ticket",
    ...
    }
    ]
    }

  • KarkuroKarkuro Posts: 7Questions: 5Answers: 0
    edited March 2016

    I modified my method a bit.

    This is my array :

       $arrayMess['data'][] = array('date' => $value->date ,'dest' => $value->recname." ".$value->recfirstname, 'message' => $value->message, 'exp' => $value->expname." ".$value->expfirstname);
    

    When I json_encode it, and echo it, I get that :

    {  
       "data":[  
          {  
             "date":"2016-03-04 15:33:15",
             "dest":"Dias Marco",
             "message":"ztest",
             "exp":"Dias Marco"
          },
          {  
             "date":"2016-03-04 15:33:15",
             "dest":"Dias Marco",
             "message":"ztest",
             "exp":"Dias Marco"
          },
    

    So it seems to be good now ?

    The thing is I try to put it in my dataTable like this :

    $('#datatable').DataTable( {
            "ajax": "<?php echo $arrayMess; ?>",
            "columns": [
                { "data": "date" },
                { "data": "dest" },
                { "data": "message" },
                { "data": "exp" }
            ]
        } );
    

    And I get on Firebug (Firefox extension) :

    SyntaxError: missing } after property list
        
    
    "ajax": "{"data":[{"date":"2016-03-04 15:33:15","dest":"Dias Marco","me
    
  • NeiculNeicul Posts: 6Questions: 3Answers: 0

    I'm pretty sure that's just a syntax error.
    You're echoing that script form a PHP file, right?
    Watch your quotation marks

  • KarkuroKarkuro Posts: 7Questions: 5Answers: 0
    edited March 2016

    Yes it's a .php file, the javascript is in the same file actually since it's the view of one of my pages. I'm gonna try to look into the quotation marks, hopefully it's the problem.

This discussion has been closed.