4

I'm attempting to use an ajax source with Datatables, and I've run into some errors in doing. Previously Ajax was not being used with Datatables, and they were working fine, but upon trying to use Ajax and JSON I have some errors.

The error I am recieving is the following:

Uncaught TypeError: Cannot read property 'length' of undefined

Edit: Upon using the revised code directly below this text, this error is no longer present but DataTables are still broken (no searching, pagination, sorting, etc...). It may help to have a live example, so try this site: fogest.com/test

To create the tables when the page loads here is the code:

$(document).ready(function() {
    $('#trades').dataTable( {
        "sDom": "<'row'<'span6'l><'span6'f>r>t<'row'<'span6'i><'span6'p>>",
        "sPaginationType": "bootstrap",
        "bProcessing": true,
        "bServerSide": true,
        "aoColumns": [
            { "mData": "id" },
            { "mData": "Minecraft_Username" },
            { "mData": "Block_Name" },
            { "mData": "Quantity" },
            { "mData": "Cost" },
            { "mData": "Trade_Status" },
          ],
        "sAjaxSource": "test.php"
    } );
} );

And sAjaxSource test.php contains the following:

<?php 
$tableName = "mctrade_trades";
$result = mysql_query("SELECT `id`, `Minecraft_Username`, `Block_Name`, `Quantity`, `Cost`, `Trade_Status` FROM $tableName");

$data = array();
while ( $row = mysql_fetch_assoc($result) )
{
    $data[] = $row;
}
header("Content-type: application/json");
echo json_encode( $data );    

?>

The output of test.php:

[{"id":"1","Minecraft_Username":"fog","Block_Name":"DIAMOND_PICKAXE","Quantity":"1","Cost":"100","Trade_Status":"1"},{"id":"2","Minecraft_Username":"fog","Block_Name":"DIAMOND_PICKAXE","Quantity":"1","Cost":"1002","Trade_Status":"1"},{"id":"3","Minecraft_Username":"fog","Block_Name":"DIAMOND_PICKAXE","Quantity":"1","Cost":"1035","Trade_Status":"1"},{"id":"4","Minecraft_Username":"fog","Block_Name":"DIAMOND_PICKAXE","Quantity":"1","Cost":"1035","Trade_Status":"1"},{"id":"5","Minecraft_Username":"fog","Block_Name":"DIAMOND_PICKAXE","Quantity":"1","Cost":"100","Trade_Status":"2"},{"id":"6","Minecraft_Username":"fog","Block_Name":"DIAMOND_PICKAXE","Quantity":"1","Cost":"100","Trade_Status":"2"},{"id":"7","Minecraft_Username":"fog","Block_Name":"DIAMOND_PICKAXE","Quantity":"1","Cost":"10000","Trade_Status":"2"}]

The table is generated correctly but due to this error, there is text saying "Processing right above the table, and you cannot use any of the functions of the datatable, such as searching.

Here is an image of what the table looks like using the above JSON: Example table output

I'm assuming the error is in my JSON output, but I do not exactly know what is wrong with it, nor what I should do to fix it. I'm pretty new to Web Development and implementing Datatables has been quite the learning curve!

ComputerLocus
  • 3,448
  • 10
  • 47
  • 96
  • What happens if you remove the `"sAjaxDataProp": "",` line in your datatable configuration? Do you still get the same error? – Tanzeel Kazi Jan 03 '13 at 06:20
  • @TanzeelKazi Nothing seems to happen when I remove that line. I've updated my post to show the new JS I'm using, but now instead of any errors, it seems like rather now the DataTable functionality is not working. Pagination is gone, search, sorting, etc all now do not work at all, just no error to explain why anymore. If it helps at all here is my site link where you can see the test: http://fogest.com/test/index.php – ComputerLocus Jan 03 '13 at 14:02

1 Answers1

6

Your JSON output is wrong for the following reasons:

  1. The iTotalRecords and iTotalDisplayRecords fields are missing. This is why the pagination (and all the other functionalities) are broken (notice the message "Showing 1 to NaN of NaN entries (filtered from NaN total entries)" in the footer section). See this page for further details on server-side processing.
  2. There is some HTML code after the JSON response.

Here is the extra HTML code (taken from test.php):

<!-- Hosting24 Analytics Code -->
<script src="http://stats.hosting24.com/count.php"></script>
<!-- End Of Analytics Code -->

In my opinion, the test.php script should be like the following:

<?php 

$link = mysqli_init();

// Adjust hostname, username, password and database name before use!
$db = mysqli_real_connect($link, "hostname", "username", "password", "database") or die(mysqli_connect_error());

$SQL = 'SELECT `id`,`Minecraft_Username`,`Block_Name`,`Quantity`,`Cost`,`Trade_Status` FROM mctrade_trades';
$result = mysqli_query($link, $SQL) or die(mysqli_error($link));

$aaData = array();
while ($row = mysqli_fetch_assoc($result)) {
    $aaData[] = $row;
}

$response = array(
  'aaData' => $aaData,
  'iTotalRecords' => count($aaData),
  'iTotalDisplayRecords' => count($aaData)
);
if (isset($_REQUEST['sEcho'])) {
  $response['sEcho'] = $_REQUEST['sEcho'];
}

header('Content-type: application/json'); 
echo json_encode($response);

?>

Be also aware that the mysql_* functions are deprecated, so you should use PDO or MySQLi instead; have a look at this answer for further details.

Community
  • 1
  • 1
  • The problem with that additional content that is being added, is that my host (Free) automatically inserts that, so I have no choice with having that. I guess I will need to change hosts, but in the meantime, I will test it locally. I will give your answer a try and get back to you on my results in another comment! Thanks! – ComputerLocus Jan 03 '13 at 22:34
  • After trying the code you supplied, I have essentially the same issues as before, except that the entries are no longer showing `NaN` they are showing the correct number of entries. Searching, and filtering (sorting) still are broken. When I try to use them, a "processing" text comes up for a split second, but nothing changes. **Edit: This is done on local host. That extra html after the JSON is not there on the localhost** – ComputerLocus Jan 03 '13 at 22:42
  • My PHP code was only an example. You can find a much better server-side PHP script [here](http://www.datatables.net/development/server-side/php_mysql). –  Jan 04 '13 at 12:52