How to make DataTables work with PHP, HTML and JavaScript?
How to make DataTables work with PHP, HTML and JavaScript?
Hello!
I have the following situation:
index.php:
echo "<div id='datagrid' ></div>";
script.js:
$('#table_id').DataTable();
$.post("pass_value.php", { 'sdb': db,
'dateFrom': window.from, 'dateTo': window.to }, function (data) {
$('#datagrid').html(data);
});
Based on the posted values I build a table.
pass_value.php:
echo "<table id='table_id'>
<tbody>
<tr>
<td>1</td>
<td>foo2</td>
<td>bar2</td>
</tr>
<tr>
<td>2</td>
<td>foo2</td>
<td>bar2</td>
</tr>
</tboby>
</table>";
Do you have any idea how to make it work?
Thanks,
Petya
This question has an accepted answers - jump to answer
Answers
Please link to a test case as required in the forum rules in future.
Also note that you do not have
-tag thead
element as required by DataTables.Finally, initialise DataTables after you put the table into the DOM.
Allan
Thanks Alan!
I cannot set up the demo because I don't find a way to add the php code (if any, please tell me how).
When I create the table the basic way it works perfectly:
http://live.datatables.net/yanosixo/1/
What I am trying to achieve is the following:
I have buttons representing different databases. When clicked the database value is send to pass_value.php where I am executing new query and I want to display the new result in the table.
Did you try initialising the DataTables after you insert the table into the DOM as I suggested above?
Beyond that I would need a link to the page to be able to help further.
Allan
I managed to do what I wanted. I initialize the dataTable and then when I click on the database button I do this:
window.table.destroy();
window.table = $("#table_id").DataTable();
However, now it's very very slow... Do you know what could be the reason?
Also I lost my event $("table").on("click", "tr", function row() {...}
as well as $('tbody tr').hover(function(){...}
You want to avoid destroying the table if you can. If you just want to clear the existing table and then add new data use the API:
clear()
androws.add()
.Allan