My problem is the following, I have a page that contains a button, clicking on it builds a table that reads data from a database. What you need to do is add the paging and searching, but it doesn't, it just builds the table.
I make the clarification that I made this example in this way because I need to build the table based on different filters.
This is my index.php
<!DOCTYPE html>
<html>
<title>Datatable</title>
<head>
<!-- Bootstrap and Jquery-->
<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" />
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery-3.3.1.min.js"></script>
<!-- Icons -->
<link rel="stylesheet" href="font/css/open-iconic-bootstrap.min.css">
<!-- Datatables-->
<script type="text/javascript" language="javascript" src="js/jquery.dataTables.js"></script>
<link rel="stylesheet" href="css/jquery.dataTables.css" type="text/css" />
<script type="text/javascript" language="javascript" src="js/script.js"></script>
</head>
<body>
<div class="container">
<h3 align="center">DataTable Example</h3>
<button type="button" onclick="show_table()"> Create </button>
<div id="mydiv">
</div>
</div>
</body>
</html>
The following function is executed in javascript when the button is clicked (script.js)
function show_table() {
var url = 'table.php';
var method = 'POST';
ajax (url, method, 'mydiv');
}
function ajax (url, method, container_id) {
try {
xhr = new XMLHttpRequest();
} catch(e) {
try{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e1) {
alert("Not supported!");
}
}
xhr.onreadystatechange = function() {
if(xhr.readyState == 4) {
document.getElementById(container_id).innerHTML = xhr.responseText;
}
}
xhr.open(method, url, true);
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send();
}
Here is the PHP that builds the table (table.php)
<?php
$connect = mysqli_connect("localhost", "root", "", "test");
$query = "select * from employee order by id desc";
$result = mysqli_query($connect, $query);
?>
<table id="employee-data" class="table table-striped">
<thead>
<tr>
<td>Employee name</td>
<td>Salary</td>
<td>Age</td>
<td>View</td>
<td>Edit</td>
<td>Delete</td>
</tr>
</thead>
<?php
while ($row = mysqli_fetch_array($result))
{
echo '
<tr>
<td>'.$row["employee_name"].'</td>
<td>'.$row["employee_salary"].'</td>
<td>'.$row["employee_age"].'</td>
<td><button type="button" class="btn btn-outline-primary"><span class="oi oi-account-login"></span></button></td>
<td><button type="button" class="btn btn-outline-primary"><span class="oi oi-pencil"></span></button></td>
<td><button type="button" class="btn btn-outline-primary"><span class="oi oi-trash"></span></button></td>
</tr>
';
}
?>
</table>
<script>
$(document).ready(function() {
$('#employee-data').DataTable();
} );
</script>
I hope you can help me with this problem, I appreciate any input.
Your problem is that you try to initialize the dataTable on page start, but you have to do it after pressing the button like so: