peace_love
peace_love

Reputation: 6461

How can I create server-side processing datatables?

I tried to create a server-side processing DataTable according to this manual:

https://datatables.net/examples/server_side/simple.html

But I do not get any results from my database.

index.php:

<link rel="stylesheet" href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css">

<table id="example" class="display" width="100%" cellspacing="0">
    <thead>
        <tr>
            <th>id</th>
        </tr>
    </thead>
    <tfoot>
        <tr>
            <th>id</th>
        </tr>
    </tfoot>
</table>
  <script>

$(document).ready(function() {
    $('#example').DataTable( {
        "processing": true,
        "serverSide": true,
        "ajax": "server.php"
    } );
} );

</script>

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>

server.php:

<?php


// DB table to use
$table = 'elephants';

// 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 ),
);

// SQL server connection information
$sql_details = array(
    'user' => 'root',
    'pass' => 'root',
    'db'   => 'animals',
    '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 )
);

and the ssp.class.php:

https://github.com/DataTables/DataTables/blob/master/examples/server_side/scripts/ssp.class.php

I do not know, what I did wrong but my result is only

id

id

Upvotes: 0

Views: 2687

Answers (1)

Rohan Kumar
Rohan Kumar

Reputation: 40639

You are initialising your code before adding dependent JS libraries,

Try it like,

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script>
// Initialise after adding Jquery and Datatable plugin
$(document).ready(function() {
    $('#example').DataTable( {
        "processing": true,
        "serverSide": true,
        "ajax": "server.php"
    });
});
</script>

Try to add field parameter in $columns array like,

$columns = array(
    array( 'db' => 'id', 'dt' => 0, 'id' )
);

Also you have 2 columns in your Datatable, but returning just 1 from Server end. So either remove second column from HTML Table or add 1 more column in $columns array.

Read more about SSP

Upvotes: 1

Related Questions