Datatables autorefresh with Ajax

Datatables autorefresh with Ajax

Nico90Nico90 Posts: 18Questions: 7Answers: 0

Hi there,

is it possible to include Ajax autorefresh on Datatables with such a code?:

<?php
$link = mysqli_connect("host", "user", "pass");
mysqli_select_db($link, "dbname");

$res = mysqli_query($link, "SELECT * FROM te_lb_load_board, te_lb_load_board_cstm WHERE te_lb_load_board.id = te_lb_load_board_cstm.id_c AND te_lb_load_board_cstm.load_status_c LIKE '%open%' ORDER BY shipping_date_c DESC, shipping_time_c ASC ");
echo "<table  class='table table-striped table-bordered'>";
echo "<tr>";

echo "<th>"; echo "Date";  echo "</th>";
echo "<th>"; echo "Time";  echo "</th>";
echo "<th>"; echo "Zip";  echo "</th>";
echo "<th>"; echo "City";  echo "</th>";
echo "<th>"; echo "Country";  echo "</th>";
echo "<th>"; echo "Date";  echo "</th>";
echo "<th>"; echo "Time";  echo "</th>";
echo "<th>"; echo "Zip";  echo "</th>";
echo "<th>"; echo "City";  echo "</th>";
echo "<th>"; echo "Country";  echo "</th>";
echo "<th>"; echo "Description";  echo "</th>";


echo "</tr>";
while ($row = mysqli_fetch_array($res)) {

    echo "<tr>";
    echo "<td>";echo $row['shipping_date_c'] ;echo "</td>";
    echo "<td>"; echo $row['shipping_time_c'];  echo "</td>";
    echo "<td>"; echo $row["billing_address_postalcode"]; echo "</td>";
    echo "<td>"; echo $row["billing_address_city"]; echo "</td>";
    echo "<td>"; echo $row["billing_address_country"]; echo "</td>";
    echo "<td>"; echo $row["arrival_date_c"]; echo "</td>";
    echo "<td>"; echo $row["arrival_time_c"]; echo "</td>";
    echo "<td>";echo $row["shipping_address_postalcode"]; echo "</td>";
    echo "<td>";echo $row["shipping_address_city"]; echo "</td>";
    echo "<td>";echo $row["shipping_address_country"]; echo "</td>";
    echo "<td>";echo $row["description"]; echo "</td>";
    echo "</tr>";

}

echo "</table>";


<?php
>
?>


Thanks,

Nico

Answers

  • allanallan Posts: 63,455Questions: 1Answers: 10,465 Site admin
    edited January 2018

    Not if you are outputting the HTML with PHP like that. You could reload the whole page with the above and that would work, but its not ajax.

    For Ajax you should populate the table with Ajax sourced data (see the manual) and then call ajax.reload() whenever you want to refresh the content.

    Allan

  • Nico90Nico90 Posts: 18Questions: 7Answers: 0

    Hi @allan,

    thank you for your answer, which method could be the best to autorefresh Datatables wwhen new records are added into the db without refreshing the browser?

    Thanks,

    Nico

  • allanallan Posts: 63,455Questions: 1Answers: 10,465 Site admin

    Using Ajax loaded data with ajax.reload() - e.g.:

    setInterval( function () {
      table.ajax.reload();
    }, 60000 ); // every 60 seconds
    

    The best way is really to use a web socket, but that's a fair bit more work.

    Allan

This discussion has been closed.