So i’m doing this function that on the change event of the select box, it will trigger an ajax call and would fetch data from the database. That part’s done. I’m getting all values i need. I place it in a table. Problem is, all the data appears in only one data cell. Here’y my code guys.
stud-home.php
<?php
include('includes.html');
include('conn.php');
$select_options =mysqli_query($conn, "SELECT DISTINCT sy from subjects");
?>
<!--Logic-->
<script>
$(document).ready(function(){
function get_subj_id() {
var filter =$("#subj-filter").val();
$.ajax({
url:'neu-server.php',
method:'POST',
data:{filter:filter},
success:function(data) {
$(".this").html(data);
}
});
}
$("#subj-filter").change(function(){
get_subj_id();
});
});
</script>
<div class='container bg-success my-2'>
<div class='row'>
<!-- content here -->
<select class='form-control my-2 mx-2' id='subj-filter'>
<option selected disabled> **Select school year**</option>
<?php
if(mysqli_num_rows($select_options) >0) {
while ($row =mysqli_fetch_assoc($select_options)) {
echo "<option value='".$row['sy']."'>".$row['sy']."</option>";
}
}
?>
</select>
<table class='table table-light table-sm'>
<thead>
<th>ID</th>
<th>Code</th>
<th>Description</th>
</thead>
<tbody>
<tr class='this'></tr>
</tbody>
<!--End of container-->
</div>
</div>
server code
<?php
include('includes.html');
$conn =mysqli_connect('localhost','root','','neu');
if (isset($_POST['filter'])) {
$filter = mysqli_real_escape_string($conn,$_POST['filter']);
$search_subject =mysqli_query($conn,"SELECT id,description,code from subjects where sy = '$filter' ");
$result =mysqli_num_rows($search_subject);
if ($result > 0) {
while ($row =mysqli_fetch_assoc($search_subject)) {
$data ="
<td>".$row['id']."</td>";
$data .="
<td>".$row['code']."</td>";
$data .="
<td>".$row['description']."</td>";
echo $data;
}
}
}
?>
2
Answers
As you are not Ending each row with tag
change this
TO This
I read your comment about actually closing the table so assuming the markup is now correct:
If you move the
class='this'
to thetbody
element each record from the db should be on it’s own row when inserted. The Javascript remains fairly much the same as the original.The closing
</option>
is and has always been entirely optional (weirdly) so perfectly safe to remove it.The PHP.
The original SQL was vulnerable to SQL injection – always use
prepared statements
when dealing with user supplied input!