I use Datatable in my web application. Following is my simple code to get data using ajax.
<script>
$(document).ready(function() {
$('#mytable').DataTable();
} );
</script>
<body>
<h2>AJAX SELECT</h2><hr>
<div align="center">
Select Team :
<select name="select" id ='teamSelect'>
<option value="">Select Value</option>
<option value="op2">Company 1</option>
</select>
</div>
<div id='tableContainer' align="center"></div>
<script>
$(function() {
$("#teamSelect").bind("change", function() {
$.ajax({
type: "GET",
url: "getData.php",
"dataSrc": "tableData",
success: function(html) {
$("#tableContainer").html(html);
}
});
});
});
</script>
and Getdata.php Code
<table id="mytable" class="display" cellspacing="0" width="50%">
<thead>
<tr>
<th>First name</th>
<th>Last Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td>Airi Satou</td>
<td>Accountant</td>
<td>Tokyo</td>
</tr>
<tr>
<td>Brielle Williamson</td>
<td>Integration Specialist</td>
<td>New York</td>
</tr>
<tr>
<td>Herrod Chandler</td>
<td>Sales Assistant</td>
<td>San Francisco</td>
</tr>
<tr>
<td>Rhona Davidson</td>
<td>Integration Specialist</td>
<td>Tokyo</td>
</tr>
</tbody>
I Link Jquery, datatable css and js both.but still It return output as normal HTML table. No console error founded. I need that data in datatable. So how can i get that.
and i also tested datatable in index.php page. It working quite good.
You are initializing datatable before table added. You need to initialize it in ajax
remove following script
<script>
$(document).ready(function() {
$('#mytable').DataTable();
} );
</script>
update ajax as below:
<script>
$(function() {
$("#teamSelect").bind("change", function() {
$.ajax({
type: "GET",
url: "getData.php",
"dataSrc": "tableData",
success: function(html) {
$("#tableContainer").html(html);
$('#mytable').DataTable({
"destroy": true, //use for reinitialize datatable
});
}
});
});
});
</script>
Put
<script>
$(document).ready(function() {
$('#mytable').DataTable();
} );
</script>
At the bottom of your Getdata.php
file also links to the datatable css and js.
Or use ajaxComplete function() to call the datatable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With