I have developed a mysql database and a php code. In php code i am using jQuery (ajax call) to fetch the data from the database. In html file i have printed datatable's table head only. Rest data i want to fetch from the database. code is given:
HTML CODE:
<div class="container box">
<div class="table-responsive">
<div id="alert_message"></div>
<table id="example" class="display">
<thead>
<tr>
<th>Student ID</th>
<th>Student Name</th>
<th>Email ID</th>
<th>Mobile</th>
<th>Status</th>
</tr>
</thead>
</table>
</div>
</div>
jQuery CODE:
<script>
$(document).ready(function() {
$('#example').dataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "fetch.php",
"type": "GET",
"datatype": "json"
}
});
});
</script>
fetch.php
<?php
$connect = mysqli_connect("localhost","root","","lib");
$sql = "SELECT StudentId, FullName, EmailId, MobileNumber, Status FROM tblstudents";
$result = mysqli_query($connect,$sql);
$json_array = array();
while ($row = mysqli_fetch_assoc($result))
{
$json_array[] = $row;
}
echo json_encode($json_array);
?>
Still the data is not printed in the datatable. What changes are necessary in jQuery?
I know this is really late, but I used the exact same code as you (thanks for that by the way!), and what made it work for me is to simply add to the JQuery code:
dataSrc = '' (after url = '...')
so that DataTables knows that it's loading an array. Putting that in made the code work fine!
In jQuery Datatables, not only you can fetch data from ajax call. you can manage page ordering, searching as well.
first of all you have to modify your javascript like this.
Then as you can see in the browsers Developer Tools -> Network tap, all the parameters that wanted for searching, sorting and ordering will be pass trough the ajax call.
you can see it by print_r($_POST) in the ajax page (in your case fetch.php) and viewing it on ajax respond in the browsers Developer Tools -> Network tap.
you can collect all of that as follows,
then you can construct the query as follows,
then to get total record count you can do as follows,
finally construct the json out put that will be sent to the front view.
That will work.