У меня есть страница постов и комментариев, над которой я работаю. Когда пользователь отвечает на комментарий, я хочу, чтобы новый добавленный комментарий отображался на экране. JQuery добавляет ответ на страницу без обновления, но я не могу получить его для привязки или прокрутки в то же время
Я пытался
location.href = "#rep_"+anchor;
однако это сделалне работает для моих комментариев, я даже пытался вручную добавить #reference
к URL-адресу без успеха.
далее я пытался использовать функцию scrollIntoView
, которая, как я считаю, будет работать, и это больше делатьсо сроками. Я использую динамический идентификатор с использованием идентификатора записи, поэтому, когда добавляется новая запись, я перенастраиваю новый идентификатор, устанавливая его в качестве идентификатора элемента от ID
до scrollto
. Когда я делаю это, я получаю следующую ошибку
sc-comments-single.js: 65 Uncaught TypeError: Невозможно прочитать свойство 'scrollIntoView' из null
Я верю в этопроисходит потому, что функция, которая создает данные комментария и ответа, не имеет нового ответа и, следовательно, не может найти элемент.
Если я получу минус 1 от нового идентификатора (последний комментарий), функция сработает и она перейдет к последнему идентификатору, но мне нужно, чтобы он был новым идентификатором.
$('#replyForm').on('submit', function(event){
event.preventDefault();
var formData = $(this).serialize();
$.ajax({
url: "php_includes/replies.php",
method: "POST",
data: formData,
dataType: "JSON",
success:function(response) {
if(!response.error) {
var anchor = "rep_"+(response.id);
$('#replyForm')[0].reset();
// $('#commentId').val('0');
// $('#message').html(response.message);
$('#comment-mess-rep').html('');
$('#comment_rep').html('');
// elmnt.scrollIntoView();
// location.href = "#rep_"+anchor;
// location.href = "#bottom";
showComments();
alert (anchor);
} else if(response.error){
$('#message').html(response.message);
}
scrolltoNewReply(anchor)
}
})
});
function scrolltoNewReply(anchor){
var elmnt = document.getElementById(anchor);
alert (elmnt);
elmnt.scrollIntoView();
}
Это довольно разочаровывает, я пытался запустить функцию прокрутки в разных местах, но с одинаковым результатом. Я думал, что мне нужна функция задержки. Я знаю, в чем проблема, но я просто не могу найти способ ее решить.
Спасибо, что уделили время
Как и было обещано, посмотрите ниже часть кода PHP
Это бит кода showComments (js) (вызов php-файла)
function showComments() {
var stat_id = getUrlParameter('stat_id');
$.ajax({
url:"php_includes/show_comments-single.php?stat_id="+stat_id,
method:"POST",
success:function(response) {
$('#showComments').html(response);
}
})
}
Это код для получения сообщений (у меня есть планы настроить оператор SQL на подготовленные операторы после того, как я разрешу)мой макет и функции, так что это не будут мои последние утверждения) Приведенный ниже код вызывается функцией showComments ();
$commentQuery = "SELECT id, parent_id, comment, sender, date FROM sc_comment WHERE parent_id = '0' and id = $status_id ORDER BY id DESC";
$commentsResult = mysqli_query($db_conx, $commentQuery) or die("database error:". mysqli_error($conn));
$commentHTML = '';
while($comment = mysqli_fetch_assoc($commentsResult)){
$commentId = $comment["id"];
$sender = $comment["sender"];
$comment_data = $comment["comment"];
$comment_date = $comment["date"];
$timeago = get_timeago_post($comment['date']);
// removed some code to shorten the snippet
$commentHTML .= "
<div id=\"$commentId\" class=\"panel panel-light mt-1 border border-secondary postMainBkg\">
<div class=\"panel-heading\">
<a href=\"home.php?u=$sender\"><img src=\"user/$sender/$senderImg\" alt=\"$sender\" style=\"width: 40px; height: 40px;\" class=\"img-fluid rounded-circle\" ></a>
By <b>$displayName</b> <small><em>$timeago</em></small>
</div>
<div class=\"panel-body text-center\">
$comment_data
</div>
<div class=\"d-flex justify-content-between px-1\">
<span class=\"status_info text-muted\">? Likes</span> <span class=\"status_info text-muted\">? Views</span> <span class=\"status_info text-muted\">? Comments</span>
</div>
<div class=\"d-flex justify-content-around py-1 border-top border-bottom border-secondary\">
$like $share
</div>
</div> ";
$commentHTML .= getCommentReply($db_conx, $commentId);
$commentHTML .= $under_line = '<div id="bottom" class="border-bottom border-secondary mb-3"></div>';
}
echo $commentHTML;
function getCommentReply($db_conx, $parentId = 0, $marginLeft = 0) {
$commentHTML = '';
$commentQuery = "SELECT id, parent_id, comment, sender, date FROM sc_comment WHERE parent_id = '".$parentId."'";
$commentsResult = mysqli_query($db_conx, $commentQuery) or die("database error: ". mysqli_error($db_conx));
$commentsCount = mysqli_num_rows($commentsResult);
if($parentId == 0) {
$marginLeft = 0;
} else if ($marginLeft == 75) {
$marginLeft = 75;
}else{
$marginLeft = $marginLeft + 25;
}
// if ($commentsCount = 0){
// $commentHTML .= $under_line = '<div class="border-bottom border-success"></div>';
// }
if($commentsCount > 0) {
while($comment = mysqli_fetch_assoc($commentsResult)){
$replysid = $comment["id"];
$sender = $comment["sender"];
$comment_data = $comment["comment"];
$comment_date = $comment["date"];
$timeago = get_timeago_post($comment['date']);
$loged_in = $_SESSION['username'];
// removed some more code to shorten the snippet
$px = "px";
$commentHTML .= "
<div id=\"rep_$replysid\" class=\"\">
<div class=\"p-block\" style=\"margin-left:$marginLeft$px\">
<div class=\"row ml-0\">
<a href=\"home.php?u=$sender\"><img src=\"user/$sender/$senderImg\" alt=\"$sender\" style=\"width: 30px; height: 30px; class=\"img-fluid rounded-circle\">
</a>
<div class=\"panel text-center\">
<div class=\"panel-heading p-header ml-1 px-1\">
<span class=\"header_text\"><b>$displayName</b></span> <span class=\"status_info\"><em>$timeago</em></span>
</div>
</div>
</div>
<div class=\"panel-body text-center status_text\">
$comment_data
</div>
<div class=\"panel-footer\" align=\"right\">
<div class=\"d-flex justify-content-around py-1 border-top border-secondary\" >
$like_count_rep
<p class=\"text-muted reply mb-0\" id=\"$replysid\" data-sender=\"$sender\"><small><em>Reply</em></small>
</p>
$like_rep
</div>
</div>
</div>
</div>";
$commentHTML .= getCommentReply($db_conx, $replysid, $marginLeft);
}
}
return $commentHTML;
}
Этот последний бит кода используется системой для сохранения ответа насообщение
<?php
include_once("db_conx.php");
if(!empty($_POST["name_rep"]) && !empty($_POST["comment_rep"])){
$parentId = $_POST["commentId_rep"];
$parentQuery = "SELECT id, parent_id,oid FROM sc_comment WHERE id = '".$parentId."'";
$parentResult = mysqli_query($db_conx, $parentQuery);
$oparent = mysqli_fetch_assoc($parentResult);
$oid = $oparent["oid"];
if($oid == 0) {
$noid = $oparent["id"];
}else{
$noid = $oparent["oid"];
}
$insertComments = "INSERT INTO sc_comment (parent_id, comment, sender, oid) VALUES ('".$_POST["commentId_rep"]."', '".$_POST["comment_rep"]."', '".$_POST["name_rep"]."', '".$noid."')";
mysqli_query($db_conx, $insertComments) or die("database error: ". mysqli_error($db_conx));
$last_id = $db_conx->insert_id;
$message = '<label class="text-success">Comment posted Successfully.</label>';
$status = array(
'error' => 0,
'message' => $message,
'id' => $last_id
);
} else {
$message = '<label class="text-danger">Error: Comment not posted.</label>';
$status = array(
'error' => 1,
'message' => $message,
'id' => $last_id
);
}
echo json_encode($status);
?>