0

Is there a way to add row as html to datatable? I understand that the suggested way of doing it is this:

$('#addRow').on( 'click', function () {
        t.row.add( [
            counter +'.1',
            counter +'.2',
            counter +'.3',
            counter +'.4',
            counter +'.5'
        ] ).draw( false );

        counter++;
    } );

But I have a complex JSON input and I want to pre process it in PHP. Is it doable or even possible?

EDIT:

So instead of doing the code above:

 t.row.add(resultfromphpserverwithalltherows);

UPDATE:

JSON output

{"student":[{"id":"2008-161","name":"Joseph Taylor","age":"20","status":"married","address":"USA","subjects":[{"math":"90","science":96,"history":99,"literature":93,"pe":"96"}],"remarks":"passed"}

and sometimes:

{"student":[{"id":"2008-161","name":"Joseph Taylor","age":"20","status":"married","address":"USA","subjects":[{"math":"90","science":96,"history":99,"literature":93,"pe":"96"}],"remarks":"passed","othersubjects":[{"applied math":"90","general science":96,"world history":99,"literature":93,"pe":"96"}],"remarks":"passed"}

So I can't really define the columns because the JSON output is dynamic and that's why I want to preprocess it in PHP first.

1 Answer 1

1

No matter how you approach this, there's going to be some significant data-formatting required.

Best approach for what you're asking: use DataTables server-side tools.

It requires including some additional components, but will simplify the javascript down to:

$('#example').DataTable( {
    "processing": true,
    "serverSide": true,
    "ajax": "../server_side/scripts/server_processing.php"
} );

...with a little tweaking, you can simplify that further:

$(function(){
    var dt = new dataTableAuto();
    dt.load();
});

function dataTableAuto() {
    this.params = {
        "processing": true,
        "serverSide": true,
        "ajax": "../server_side/scripts/server_processing.php"
    };

    this.load = function() {
        $('#example').DataTable( this.params );
    }
}

php ajax server to send raw JSON as a single row

Simply send an ajax request to php which includes the counter, then respond with a json array matching what you want to build.

Javascript snippet

counter = 0;

$.ajax({
    url: '[your url]',
    type: 'post',
    data: {"counter":counter},
    contentType: "application/json",
    dataType: 'json',
    success: function(response){
        t.row.add(JSON.parse(response)).draw( false );
        counter++;
    },
});

php Snippet

$jsonString = file_get_contents('php://input');
$data = json_decode($jsonString);
$counter = $data['counter'];
$totalRows = 10;

for( $i = 0; $i < $totalRows; $i++) {
    $result[] = $counter .".". $i;
}

header('Content-Type: application/json', true, 200);
echo json_encode($result);
exit;

DataTables pure AJAX approach

javascript

$(function(){
    t = $('#example');

    $.ajax({
        url: '[your url]',
        type: 'post',
        data: {"classID":12},
        contentType: "application/json",
        dataType: 'json',
        success: function(response){
            t.DataTable( JSON.parse(response) );
        },
    });
});

php

$jsonString = file_get_contents('php://input');
$data = json_decode($jsonString);
$classID = intval($data['classID']);

$cols = array('Name', 'Position', 'Score');
foreach ( $cols as $colName ) {
    $entry = new stdClass();
    $entry->title = $colName;
    $result['columns'][] = $entry;
}

$result = // some query [ex: get rows by class id]

foreach( $result as $row) {
    $thisRow = array();
    foreach ( $cols as $colName ) {
        $thisRow[] = $row['$colName']
    }
    $result['data'][] = $thisRow;
}

header('Content-Type: application/json', true, 200);
echo json_encode($result);
exit;

This should produce an object similar to:

{
    data: [
        ['Joseph Taylor', '22', '90']
    ],
    columns: [
        { title: "Name" },
        { title: "Position" },
        { title: "Score" }
    ]
}
Sign up to request clarification or add additional context in comments.

2 Comments

thank you... but the thing is... columns are dynamic.. some columns may present in one instance and may not present on other instance..
then either build the entire table into the JSON response with DataTables AJAX, or use the DataTables server-side approach (which ultimately is the same thing).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.