Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataTables not showing JSON data

Here is my HTML

    <table id="dt">
        <thead>
            <tr>
                <th>make</th>
                <th>model</th>
                <th>serial</th>
                <th>status</th>
                <th>User</th>
                <th>dept</th>
                <th>location</th>
        </thead>
        <tbody>
            
        </tbody>
        <tfoot></tfoot>
    </table>

And here is my JS

    <script type="text/javascript" language="javascript" >
         
        $(document).ready(function() {
            
            $.post("json.php",function(data){
                $('#dt').DataTable( {
                    "aaData": data,
                    "aoColumns": [
                            {"mDataProp": "make"},
                            {"mDataProp": "model"},
                            {"mDataProp": "serial"},
                            {"mDataProp": "status"},
                            {"mDataProp": "user"},
                            {"mDataProp": "dept"},
                            {"mDataProp": "location"}
                        ]
                });
            });
    
        } );
    </script>

And here is json.php

    
    $data = Array ();
    $data[] = array("make" => "Hp", "model" => "jhbh", "serial" => "kjkhn", "status" => "active", "user" => "John Doe", "dept" => "Manufacturing Services", "location" => "Bindura");
    $data[] = array("make" => "Dell", "model" => "Vostro", "serial" => "kjkhn", "status" => "active", "user" => "Percy Holdin", "dept" => "Manufacturing Services", "location" => "Kwekwe");
    
    echo json_encode($data,JSON_PRETTY_PRINT);

I have made an edit to this question, because now I want to get dyanmic data.

Error:

DataTables warning: table id=dt - Requested unknown parameter 'make' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4

But I havent found anything useful from that help link

like image 331
Redgren Grumbholdt Avatar asked Feb 16 '26 16:02

Redgren Grumbholdt


1 Answers

JSON format should be like this as in this example: https://datatables.net/examples/data_sources/ajax.html

{
    "data": [
        [
            "Hp",
            "jhbh",
            "kjkhn",
            "active",
            "John Doe",
            "Manufacturing Services",
            "Bindura"
        ]
    ]
}

Example on how to format json like this in php(well, one way):

$data = (object) [
    'data' => [[
        'test',
        'test',
        'test'
    ]]
];
echo json_encode($data);

And live example: http://sandbox.onlinephpfunctions.com/code/632c288c6c743da25e49958c204a8d4e0a936b54

like image 134
Roland Ruul Avatar answered Feb 18 '26 06:02

Roland Ruul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!