0

Intro: I am making a server-side datatables using ajax in datatables.net that can be found below: https://databasetable-net.000webhostapp.com/

Errors: The data in the table returns as 'undefined' instead of the actual data (click above link to see). There are no errors in the console or in the datatables dubug tracer which is why I am now seeking help.

Index.php

$(document).ready(function() {
    $('#example').DataTable( {
        "processing": true,
        "serverSide": true,
            "ajax": {
                "url": "server.php",
                "type": "POST"
            },
            "columns": [
                { "data" : "id"},
                { "data" : "first_name"},
                { "data" : "last_name"},
                { "data" : "position"},
                { "data" : "date"},
                { "data" : "updated"},
            ],
});
 }); 
$(document).ready(function(){ $.getJSON('server.php', function(data){
    var employee_data=''; 
    $.each(data, function(key,value){ 
    employee_data+='<tr>';
    employee_data+='<td>'+value.id+'</td>';
    employee_data+='<td>'+value.first_name+'</td>';
    employee_data+='<td>'+value.last_name+'</td>';
    employee_data+='<td>'+value.position+'</td>';
    employee_data+='<td>'+value.date+'</td>';
    employee_data+='<td>'+value.updated+'</td>';
 }); 
    $('#example').append(employee_data);
    }); 
}); 
  </script>

<table id="example" class="display" style="width:100%">
        <thead>
            <tr>
                <th>ID</th>
                <th>First name</th>
                <th>Last name</th>
                <th>Position</th>
                <th>Date</th>
                <th>Updated</th>
            </tr>
        </thead>
        <tfoot>
            <tr>
             <th>ID</th>
                <th>First name</th>
                <th>Last name</th>
                <th>Position</th>
                <th>Date</th>
                <th>Updated</th>
            </tr>
        </tfoot>
    </table>

<?php
$records = mysqli_query($con, "SELECT * FROM employees");
$totalData= $records->num_rows;
$totalFiltered=$totalData;
$data=array();
while ($row = mysqli_fetch_array($records)) { 
    $subdata=array();
    $subdata[]=$row[0]; //id
    $subdata[]=$row[1]; 
    $subdata[]=$row[2]; 
    $subdata[]=$row[3]; 
    $subdata[]=$row[4]; 
    $subdata[]=$row[5]; 
    $data[]=$subdata;
}

$requestData= $_REQUEST;
//https://www.datatables.net/forums/discussion/comment/94864/

$json_data = array(
                  "draw" => intval(isset($_GET['draw'])), 
                  "recordsTotal"    => intval( $totalData ), 
                  "recordsFiltered" => intval( $totalFiltered ),
                  "data"            => $data //How To Retrieve This Data
                 );

echo json_encode($json_data);  
?>

Server.php

$table = 'employees';

// Table's primary key
$primaryKey = 'id';

// Array of database columns which should be read and sent back to DataTables.
// The `db` parameter represents the column name in the database, while the `dt`
// parameter represents the DataTables column identifier. In this case simple
// indexes
$columns = array(
    array( 'db' => 'id', 'dt' => 0 ),
    array( 'db' => 'first_name', 'dt' => 1 ),
    array( 'db' => 'last_name',  'dt' => 2 ),
    array( 'db' => 'position',   'dt' => 3 ),
    array( 'db' => 'date',     'dt' => 4 ),
     array( 'db' => 'updated',     'dt' => 5 ),
);

// SQL server connection information
$sql_details = array(
    'user' => 'id3741634_username',
    'pass' => 'password',
    'db'   => 'id3741634_database',
    'host' => 'localhost'
);

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * If you just want to use the basic configuration for DataTables with PHP
 * server-side, there is no need to edit below this line.
 */

require( 'ssp.class.php' );

echo json_encode(
    SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns )
);

Conclusion: Sorta like this article but I did not use stringify:JSON returning undefined values

I mostly used this article for the foundation of my code. https://datatables.net/examples/data_sources/server_side

I am unsure how to go about this issue with no errors and little JSON experience. I suspect my issue maybe something minor. Please let me know if I can make any changes to improve my post. Thanks!

1
  • I have been focused on getting the data to appear (which is the hardest part) so originally I had in the HTML to get a foundation. I suppose I should now remove the HTML (we'll see what happens). Commented Apr 5, 2018 at 23:45

1 Answer 1

0

1) Get rid of that initial $.getJSON() call manually inserting html. When you use datatables with ajax sourced data, you need to let datatables build the html. As it is you are inserting rows (and an implied <tbody> after the <tfoot>) which is also problematic.

2) Your ajax calls including the initial $.getJSON() are all returning 0 records, and and empty array. That's why all of the cell values are undefined. those rows actually should not exist ... but regardless of that, your Server.php scripts is not returning any rows.

If you try changing the Show XX Entries select menu at the top left corner and you will see the table get updated properly with server side data. Notice how it now shows (correctly) "No data available in table".

Sign up to request clarification or add additional context in comments.

13 Comments

Ok thanks for responding. I am assuming delete the "$.getJSON('server.php', function(data)" part (or the whole section?).
And yes I know something is probably wrong with the encode json part but I wanted a second opinion first without saying anything. I am suspecing the code as follows belongs in the server.php part and not the index? I realized it is not triggering properly. "draw" => intval(isset($_GET['draw'])), "recordsTotal" => intval( $totalData ), "recordsFiltered" => intval( $totalFiltered ), "data" => $data //How To Retrieve This Data ); echo json_encode($json_data);
yes - datatables should handle everything relating to building the table body. as for why there's no data being returned you'll need to check you query and database
as far as I can see, the response is fine. it's properly structured and the draw count is getting updated. you just need to return something other than an empty array
Ok thanks for help. I might post on datables.net/forums to see why nothing is getting displayed on the server-side. I followed the instructions step by step so as you, I am puzzled. I tried adding the $.getJson part because I saw nothing wrong with the server.php
|

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.