I am working on a comment system, and I am trying to build a function that queries and displays 10 newest comments from database using ajax.
The problem I am having is that, I just can't figure out how to display multiple rows using ajax and json_encode.
When I display multiple rows with php, I use .=, which is so simple, but with ajax and json_encode, I can only display a single result with my knowledge so far.
Below is the pure PHP version of my code to display multiple rows
public function display_comment(){
$query = "SELECT * FROM 'comment' WHERE 'user_id' = $user_id ORDER BY 'save_time' DESC LIMIT 10";
$result = $database->query($query);
foreach($result as $row){
$user_id = $row['user_id'];
$user_name = $row['user_name'];
$comment = $row['comment'];
$all_comments .= '<div id="' . $user_id . '"><span>' . $user_name . '</span><span>' . $comment . '</span></div>';
}
}
Using ajax and json_encode, this is how I return a single result
public function display_comment(){
$query = "SELECT * FROM 'comment' WHERE 'user_id' = $user_id ORDER BY 'save_time' DESC LIMIT 10";
$result = $database->query($query);
foreach($result as $row){
$user_id = $row['user_id'];
$user_name = $row['user_name'];
$comment = $row['comment'];
$json_array = array("user_id" => $user_id, "user_name" => $user_name, "comment" => $comment);
header('Content-type:application/json');
exit(json_encode($json_array)); // I am using exit instead of echo, because somehow if I use echo, it returns entire html page.
}
}
jQuery part
$(document).on("click","#view_comment",function(e){
e.preventDefault();
$("#view_comment").text("loading..");
var view_comment = $(this).val(); // Don't worry about this
$.ajax({
type:"post",
data:{"view_comment":view_comment},
dataType:"json",
success:function(data){
$('#ajax_comment').html('<div id="' + data.user_id + '"><span>' + data.user_name + '</span><span>' + data.comment + '</span></div>');
},
error:function(data){
// Error code
}
});
});
How should I change my code in order to display multiple rows using json_encode?
Thank you so much in advance!