AJAX Datasouce - is this the best way of creating it?

AJAX Datasouce - is this the best way of creating it?

matyhatymatyhaty Posts: 11Questions: 1Answers: 0
edited September 2011 in DataTables 1.8
Hi All

Ive been using Datatables for a little while now, but by no means close to an expert (as the below will show!)

Im looking to move from DOM source to AJAX
Im using Codeigniter for the project, along with Datamapper. Datamapper is a ORM which creates a object. In the below code the object is $persons.

I need to be able to 'refresh' the data (hence moving away from DOM).
AJAX would be the better way, however the code below seems a long winded way for creating the array

Can anyone point me to a better place?

Thanks

[code]

<?php
$cols = array(
'Username' => 'username',
'Firstname' => 'firstname',
'Surname' => 'surname'
);

$aoColumns = '';
foreach($cols as $ckey => $cval)
{
$aoColumns .= '{ "sTitle": "'.$ckey.'" },
';
}


$aaData = '';
foreach($persons as $p)
{
$aaData .= '[ ';
foreach($cols as $ckey => $cval)
{
$aaData .= '"'.$p->$cval.'", ';
}
$aaData .= ' ], ';
}

?>


{
"aaData": [<?php echo $aaData; ?>],
}



[/code]

Replies

  • fbasfbas Posts: 1,094Questions: 4Answers: 0
    edited September 2011
    PHP 5.2+ comes with a function json_encode() that will convert your PHP arrays/objects into JSON. If you have under 5.2, you can download a suitable module to do the same thing at http://www.boutell.com/scripts/jsonwrapper.html

    [code]
    <?php
    $cols = array(
    'Username' => 'username',
    'Firstname' => 'firstname',
    'Surname' => 'surname'
    );

    $json_object = array(
    "aaData" => $cols
    );

    echo json_encode($json_object);

    ?>
    [/code]
This discussion has been closed.