Dynamically get column names in $aColumns arrary in datatables

筅森魡賤 提交于 2019-12-01 18:58:23

This is a very simple way for creating HTML from JSON data dynamically. It doesn't use server side processing though.

JavaScript

$(document).ready(function() {
    $(".abutton").click(function() {
        $('#myDatatable_wrapper').detach(); //Remove existing table
        var table = '<table id="myDatatable" class="table"><thead><tr>';
        $.ajax({
            url: 'dt.php',
            data: "table_id="+$(this).attr("id"),
            type: "POST",
            success: function (data) {
                $.each(data.aoColumns, function(key, value) {
                    table += "<th>"+value+"</th>";
                });
                table += "</tr></thead><tbody>";
                $.each(data.aaData, function(key, row) {
                    table += "<tr>";
                    $.each(row, function(key, fieldValue) {
                        table += "<td>"+fieldValue+"</td>";
                    });
                    table += "</tr>";
                });
                table += '<tbody></table>';
                $('.container').html(table);
                $('#myDatatable').dataTable();
            },
            dataType: "json"
        });
    });
});

PHP

$table_id = filter_input(INPUT_POST, "table_id", FILTER_SANITIZE_STRING);
$dbconn = mysqli_connect("localhost", "username", "password");

if($table_id == "table1") {
    $sql_query = mysqli_query($dbconn, 'SELECT * FROM display_branch');
}
else {
    $sql_query = mysqli_query($dbconn, 'SELECT * FROM display_marks');
}

if(mysqli_num_rows($sql_query) == 0) {
    echo "Check your ID";
    exit(1);
}
$data = array();
$data['aaData'] = array();
while($row = mysqli_fetch_assoc($sql_query)) {
    $data['aaData'][] = $row;
}

$data['aoColumns'] = array();
while($finfo = mysqli_fetch_field($sql_query)) {
    $data['aoColumns'][] = $finfo->name;
}
echo json_encode($data);

HTML

<button id="table1" class="abutton">Table 1</button><br /><button id="table2" class="abutton">Table 2</button>
<div class="container"></div>

Hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!