Отображение комментариев для всех сообщений

У меня есть система постов и комментариев. Что-то вроде системы постов и комментариев Facebook. Сообщение отображается правильно, я могу оставить комментарий ко всем сообщениям. Но комментарии отображаются только для первого поста, то есть поста, отображаемого сверху. ,
Проблема, по которой мне нужна ваша помощь, заключается в следующем:
-Комментарии для каждого из сообщений должны отображаться соответственно.

Это то, что я сделал.
Посмотреть:

  <div class="box box-widget">
<div class="box-header with-border">
<div class="user-block">

<span class="description">Shared publicly - <?php echo time_ago($post['post_date'])?></span>

</div>
</div>

<div class="box-body" style="display: block;">
<img class="img-responsive show-in-modal" src="<?php echo base_url('post_file/'.$post['post_image'])?>" alt="">
<input type="hidden" id="stid" value="<?php echo $post['spid']; ?>">
<p><?php echo $post['postcontent']?></p>
<button type="button" class="btn btn-default btn-xs"><i class="fa fa-share"></i> Share</button>
<div>

<input type="hidden" id="pl_postid" name="pl_postid" value="<?php echo $post['spid']; ?>">

<button type="button" class="btn btn-default btn-xs"><i class="fa fa-thumbs-o-up"></i> Like</button>
</div>
<span class="pull-right text-muted"><?php //echo $countlikes ?> likes - 3 comments</span>

</div>
<div id="display_comment"></div>
<div class="box-footer" style="display: block;">
<form id="com" class="com" method="post">
<div class="img-push">
<input type="hidden"  class="status_id" id="status_id" name="status_id" value="<?php echo $post['spid']; ?>">

<textarea  name="comment" id="comment" class="form-control input-sm comment" placeholder="Press enter to post comment"></textarea>

<div class="box-footer box-form">
<btn class="btn btn-azure btn-sm pull-right commentbt" id="commentbt">Comment</btn>
<ul class="nav nav-pills">
<li><i class="fa fa-bullhorn"></i></li>

</ul>
</div>
</div>
</form>
</div>

</div>
<?php endforeach;?>

Jquery:

$(".commentbt").click(function(){
var status_id = $(this).closest("div.img-push").find("input[name='status_id']").val();
var comment = $(this).closest("div.img-push").find("textarea[name='comment']").val();
alert(comment);

var dataString = 'status_id='+ status_id +'&comment='+ comment;
if(comment==''||status_id==''){
alert('Can not send empty comment')
}
else{
$('#display_comment').show();
//$("#display_comment").fadeIn(100).html('<img src="<?php //echo base_url();?>uploads/ajax-loader.gif" />Loading Comment...');
$.ajax({
type:"POST",
url:"<?php echo site_url('user/postcomment')?>",
data:dataString,
cache:false,
success: function () {
$(document).ready(function(){
var status_id = $("#stid").val();
$.post('<?php echo site_url('user/getcomments');?>',
{
status_id:status_id
},
function(data){
$("#display_comment").html(data);
});
});


$('#com')[0].reset();
}
});
}return false;
});
});

Спасибо

0

Решение

HTML исправления:

Не используйте то же самое ID на разных элементах, как вы делаете с display_comment, Вы создаете набор сообщений с циклом foreach, так что это создаст несколько элементов с одинаковым ID, Вместо этого используйте пользовательский класс. Remenber не должно быть более одного предмета с одинаковым ID, Элементы, которые были исправлены, следующие:

<input type="hidden" id="stid" value="<?php echo $post['spid'];?>">

<input type="hidden" id="pl_postid" name="pl_postid" value="<?php echo $post['spid']; ?>">

<div id="display_comment"></div>

<form id="com" class="com" method="post">

<input type="hidden" class="status_id" id="status_id" name="status_id" value="<?php echo $post['spid'];?>">

<textarea name="comment" id="comment" class="form-control input-sm comment" placeholder="Press enter to post comment"></textarea>

<btn class="btn btn-azure btn-sm pull-right commentbt" id="commentbt">Comment</btn>

Так как вы создаете несколько box-widgetпредыдущие элементы будут генерировать несколько из них с одинаковыми ID, Фиксированный код будет выглядеть так:

<div class="box box-widget">

<div class="box-header with-border">
<div class="user-block">
<span class="description">Shared publicly - <?php echo time_ago($post['post_date'])?></span>
</div>
</div>

<div class="box-body" style="display:block;">
<img class="img-responsive show-in-modal" src="<?php echo base_url('post_file/'.$post['post_image'])?>" alt="">
<input type="hidden" class="stid" value="<?php echo $post['spid'];?>">
<p><?php echo $post['postcontent']?></p>
<button type="button" class="btn btn-default btn-xs">
<i class="fa fa-share"></i> Share
</button>
<div>
<input type="hidden" class="pl_postid" name="pl_postid" value="<?php echo $post['spid']; ?>">
<button type="button" class="btn btn-default btn-xs">
<i class="fa fa-thumbs-o-up"></i> Like
</button>
</div>
<span class="pull-right text-muted"><?php //echo $countlikes ?> likes - 3 comments</span>
</div>

<div class="display_comment"></div>

<div class="box-footer" style="display:block;">
<form class="com" method="post">
<div class="img-push">
<input type="hidden" class="status_id" name="status_id" value="<?php echo $post['spid'];?>">
<textarea name="comment" class="form-control input-sm comment" placeholder="Press enter to post comment"></textarea>

<div class="box-footer box-form">
<btn class="btn btn-azure btn-sm pull-right commentbt">Comment</btn>
<ul class="nav nav-pills">
<li><i class="fa fa-bullhorn"></i></li>
</ul>
</div>
</div>
</form>
</div>

</div>

JQUERY Исправления:

1) Основная проблема в этом разделе заключается в том, что IDи у вас было несколько элементов с одинаковым IDТаким образом, вы, вероятно, нацеливались только на первый элемент с этими ID который появляется в HTML. Итак, как поступить? Попробуйте найти элементы по их связи с нажатой кнопкой, например, подход, который вы используете для:

var status_id = $(this).closest("div.img-push").find("input[name='status_id']").val();

2) Другая проблема заключалась в использовании $(document).ready() внутри вызова Ajax, который был удален.

Фиксированный код должен выглядеть так:

$(".commentbt").click(function()
{
var status_id = $(this).closest("div.img-push").find("input[name='status_id']").val();
var comment = $(this).closest("div.img-push").find("textarea[name='comment']").val();

alert(comment);

var dataString = 'status_id=' + status_id + ' &comment=' + comment;

if (comment == '' || status_id == '')
{
alert('Can not send empty comment')

// Finish function here if error detected!
return;
}

// The next line was fixed!
//$('#display_comment').show();
var dComment = $(this).closest(".box-widget").find(".display_comment");
dComment.show();

// The next line was also wrong (Homework for you...)
//$("#display_comment").fadeIn(100).html('<img src="<?php //echo base_url();?>uploads/ajax-loader.gif" />Loading Comment...');

// Save clicked button object, we going to need it inside the ajax.
var clickedBtn = $(this);

$.ajax({
type: "POST",
url: "<?php echo site_url('user/postcomment')?>",
data: dataString,
cache: false,
success: function()
{
// Wrong again, the next line was fixed!!
//var status_id = $("#stid").val();
var status_id = clickedBtn.closest(".box-widget").find("input.stid").val();

console.log("Getting comments for status_id = " + status_id);

$.post(
"<?php echo site_url('user/getcomments');?>",
{status_id: status_id},
function(data)
{
// Wrong again! Fixed!
//$("#display_comment").html(data);
dComment.html(data);
}
);

// Another error, guess what...
//$('#com')[0].reset();
clickedBtn.closest("form.com").reset();
}
});
});

Наконец, я должен сказать, я действительно сомневаюсь, что ваш код все еще будет работать на
В конце концов, все изменения, которые я сделал, но я надеюсь, что ты хоть
понял основные проблемы, которые вы совершали.

0

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector