I am working on this program. The program displays the topics under a specific subject.
My main question is, will the DataTable work in this kind of setup?
This is the code in HTML.
<div class="table-responsive" id="subject_container">
<table id="tbl_subject" class="table table-striped">
<thead>
<tr>
<th>Chapter</th>
<th>Topic</th>
<th>Content</th>
</tr>
</thead>
<tbody id="disp_topics"></tbody>
</table>
</div>
This is the code snippet in jquery:
$(function(){
//this is only for simplification. Subjectid will be coming from a select input.
let subjectid = 1;
get_topics(subjectid);
//this part right here. If this cannot work, is there a way to make it work?
$('#tbl_subject).DataTable();
});
function get_topics(subjectid){
$.ajax({
url: 'includes/subject_handler.php',
method: 'POST',
data: {
key: 'get_topics',
subjectid: subjectid
},
success: function(data){
$('#disp_topics).html(data);
}
});
This is the code of includes/subject_handler.php: I am using keys since there are other tasks handled by this same script file. Thank you for understanding.
if($_POST['key'] == 'get_topics'){
$subjectid = $_POST['subjectid'];
$data = '';
if(!empty($subjectid)){
$sql = "SELECT topic.subjectid, chapter, topic, content FROM topic INNER JOIN subject
ON subject.subjectid=topic.subjectid WHERE topic.subjectid = ?";
$stmt=$db->prepare($sql);
$stmt->bindValue(1, $subjectid);
$stmt->execute();
if($stmt->rowCount() > 0){
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $row){
$data .= '<tr>
<td>'.$row['chapter'].'</td>
<td>'.$row['topic'].'</td>
<td>'.$row['content'].'</td>
</tr>';
}
exit($data);
}
}
}