Reputation: 1129
I have gone through several answers on SO as well as a few tutorials and the documentation on ajax/dataTables. My dataTable will still not populate with JSON data.
HTML:
<table id="table" class="table table-striped table-bordered table-hover" cellspacing="0" width="100%">
<thead>
<tr>
<th>Status</th>
<th>Student Name</th>
<th>Exam Name</th>
<th>School</th>
<th colspan="2">Action</th>
</tr>
</thead>
<tfoot>
<th>Status</th>
<th>Student Name</th>
<th>Exam Name</th>
<th>School</th>
<th colspan="2">Action</th>
</tfoot>
</table>
Javascript:
<script type="text/javascript">
$(document).ready(function() {
// Datatables
$('#table').DataTable({
"url": "<?php echo site_url('exams/ajax_list'); ?>",
});
});
</script>
ajax_list PHP function in Exams controller:
public function ajax_list() {
$list = $this->exam_model->get_datatables();
$data = array();
foreach ($list as $exam) {
$row = array();
$row[] = $exam->exam_status;
$row[] = $exam->first_name . " " . $exam->last_name;
$row[] = $exam->exam_name;
$row[] = $exam->exam_school;
$data[] = $row;
}
echo json_encode($data);
}
From what I can see when navigating to the method, the json_encode outputs correctly, but the dataTable is still empty.
Am I missing anything?
Upvotes: 0
Views: 1606
Reputation: 5517
Ok I finally got it to work... Thanks for giving me the chance to play with this as its all brand new to me. It was a bit of a bugga, but like everything else it turns out to be simple.
I didn't set this up in CI but that wont matter...
After drudging through the documentation I came up with this...
1.Change your "url" to "ajax". I'll assume your path you use is correct. Alter what I have to yours.
<script type="text/javascript">
$(document).ready(function () {
// Datatables
$('#table').DataTable({
"ajax": "./ajax_list.php" // change this to suit.
});
});
</script>
2. Remove the colspan="2" in your th tags. It don't like it unless you use some other option I didn't look into...
3. And finally change your json_encode to...
echo json_encode(['data'=>$data]);
And hopefully that gets you up and running... The documentation is pretty good so I suggest giving that a good going over.
Upvotes: 1