Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize dataTable from separate .php table

I am trying to initialize a dataTable from a separate .php file that builds a table. It builds the table okay, but the dataTable properties do not seem to be in effect.

Here is my code:

index.php

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<html lang="en">
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        <script type="text/javascript" language="javascript" src="jquery.js"></script>
        <script type="text/javascript" language="javascript" src="jquery.dataTables.js"></script>
        <script type="text/javascript" charset="utf-8">
            $(document).ready(function() {
                $('#live_table').load("table.php");
                var refreshId = setInterval(function() {
                    $('#live_table').load("table.php");
                }, 2000);
                $.ajaxSetup({ cache: false });
                $('#data').dataTable();
            });
        </script>
        <title></title>
    </head>
    <body>
        <div id="live_table">
        </div>
    </body>
</html>

table.php

<table id="data">
    <thead>
        <tr>
            <th>Foo</th>
            <th>Bar</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1</td>
            <td>2</td>
        </tr>
        <tr>
            <td>3</td>
            <td>4</td>
        </tr>
    </tbody>
</table>

index.php is meant to refresh the table every 2000ms and table.php is actually more complex in my real situation and requires conditional cell backgrounds and links which is why I didn't choose to use the server side processing (JSON) for table data.

Any idea why the $('#data').dataTable(); command isn't working?

like image 632
Das.Rot Avatar asked Sep 12 '26 05:09

Das.Rot


1 Answers

I think it is not loading because you are using a selector that does not exist yet.

Try:

$(document).ready(function() {
            $('#live_table').load("table.php");
            var refreshId = setInterval(function() {
                $('#live_table').load("table.php");
            }, 2000);
            $.ajaxSetup({ cache: false });
            $('#data').dataTable(); //This line should be in table.php

Technically there is no element #data in the DOM. You should put the table initialization in the table.php file.

like image 184
Drakkainen Avatar answered Sep 14 '26 18:09

Drakkainen



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!