jQuery не добавляет комментарий

Таким образом, этот jQuery должен представить комментарий о статусе социального сайта, над которым я работаю.

В основном моя проблема проста и понятна. Я не могу заставить jQuery добавить к ближайшему div. Не дополняет ближайший .status-comment который является div, в который обернуты комментарии..

Как вы можете видеть, у меня есть предупреждение, которое будет отображать "Привет", которое работает, когда я публикую комментарий. Так что я знаю, что это далеко в сценарии, оно просто не добавится. я не знаю почему. Любая помощь будет оценена моими друзьями.

    $(".add-comment").bind("submit", function() { 
 var comment = $(this).closest(".commentInput").attr('value'); 
 if(comment != ""){ 
  $.ajax({ 
   type : "POST", 
   dataType : "json", 
   cache : false, 
   url : "/ajax/add-comment.php", 
   data : $(this).serializeArray(), 
   success : function(result) { 
    if(result.result == "success"){ 
    alert("hi");
      $(this).closest('.status-comment').append("<p><a href='/profile?id=<?php echo $acct['id']; ?>'><img class='statusThumbnail img-thumbnail' src='/userphotos/<?php echo $acct['photo']; ?>'></a> <span><strong><?php echo $acct['first']; ?> <?php echo $acct['last'];?></strong></span></p><p><span>"+comment+"</span></p><hr>");
      $("#comment").val("");         
    }else{ 
     alert("Well it looks like you failed");
    } 
   }, 
   error : function() { 
    alert("An error occurred, please try again later."); 
   } 
  }); 
 }else{ 
  alert("You should probably write a comment before posting it");
 } 
 return false;
});

А вот HTML-разметка, echo'd в PHP

Ввод комментария для отправки комментария:

<!-- comment box -->
        <form class="add-comment" method="post">
        <img class="comment-thumbnail" src="/userphotos/'.$acct['photo'].'"/> <span><input type="text" name="comment" class="form-control commentInput" placeholder="Comment" autocomplete=off>
        <input type="hidden" name="pid" value="'.$aStatus['status']['id'].'">
        </form></span></div>
        <!-- end comment box -->

А вот макруп, из которого повторяются все комментарии

echo '<div class="status-container">';
    foreach($status as $aStatus){
        echo '<div id="post_id_'.$aStatus['status']['id'].'" class="panel panel-default status post-box">';
        echo '<div class="panel-heading">
        <img class="statusThumbnail img-thumbnail" src="/userphotos/'.$aStatus['user']['photo'].'"/> <h6><a href="/profile?id='.$aStatus['user']['id'].'">'.$aStatus['user']['first'].' '.$aStatus['user']['last'].'</a></h6></div>';
        echo '<div class="panel-body">';
        echo '<p>'.$aStatus['status']['status'].'</p>';
        echo '<p><a><i class="glyphicon glyphicon-thumbs-up"></i> Like</a> · <a style="cursor:pointer;" class="status-comment-link"><i class="glyphicon glyphicon-comment"></i> Comment</a> - <abbr style="font-weight:bold; border-bottom:none;" title="'.date("l, F jS, Y g:i:s A",$aStatus['status']['post_time']."").'">about '.ago($aStatus['status']['post_time']."").'</abbr></p>';
        echo '</div>';
        echo '<div class="panel-footer">';
        echo '<div class="status-comment">';

Отношения между status-comment а также add-comment

echo '<div class="status-comment">';

    $comment = $account->get_comments($aStatus['status']['id']);
    if(!isset($comment['error'])){
        foreach($comment as $aComment){
            echo'

        <p><a href="/profile?id='.$aComment['user']['id'].'"><img class="statusThumbnail img-thumbnail" src="/userphotos/'.$aComment['user']['photo'].'"/></a> <span><strong>'.$aComment['user']['first'].' '.$aComment['user']['last'].'</strong></span></p>
        <p><span>'.$aComment['comment']['comment'].'</span></p>
        <hr>';
        }
    }

echo    '
        </div>
        <!-- comment box -->
        <form class="add-comment" method="post">
        <img class="comment-thumbnail" src="/userphotos/'.$acct['photo'].'"/> <span><input type="text" name="comment" class="form-control commentInput" placeholder="Comment" autocomplete=off>
        <input type="hidden" name="pid" value="'.$aStatus['status']['id'].'">
        </form></span></div>
        <!-- end comment box -->';

        echo '</div>';

1 ответ

Проблема в ключевом слове this внутри обработчика успеха AJAX не ссылается на add-comment элемент, вы можете использовать переменную замыкания, как показано ниже

$(".add-comment").bind("submit", function () {
    var $this = $(this);
    //use val() to get the value, also you may have to use `$this.find(".commentInput").val()`
    var comment = $.trim($this.closest(".commentInput").val());
    if (comment != "") {
        $.ajax({
            type: "POST",
            dataType: "json",
            cache: false,
            url: "/ajax/add-comment.php",
            data: $(this).serializeArray(),
            success: function (result) {
                if (result.result == "success") {
                    alert("hi");
                    //this here does not refer the `add-comment` element, use a closure variable
                    $this.closest('.status-comment').append("<p><a href='/profile?id=<?php echo $acct['id']; ?>'><img class='statusThumbnail img-thumbnail' src='/userphotos/<?php echo $acct['photo']; ?>'></a> <span><strong><?php echo $acct['first']; ?> <?php echo $acct['last'];?></strong></span></p><p><span>" + comment + "</span></p><hr>");
                    $("#comment").val("");
                } else {
                    alert("Well it looks like you failed");
                }
            },
            error: function () {
                alert("An error occurred, please try again later.");
            }
        });
    } else {
        alert("You should probably write a comment before posting it");
    }
    return false;
});

Проблема оказалась в том, что status-comment элемент не был предком элемента add-comment элемент. Так что ответ был

$this.closest('.panel').find('.status-comment').append("<p><a href='/profile?id=<?php echo $acct['id']; ?>'><img class='statusThumbnail img-thumbnail' src='/userphotos/<?php echo $acct['photo']; ?>'></a> <span><strong><?php echo $acct['first']; ?> <?php echo $acct['last'];?></strong></span></p><p><span>" + comment + "</span></p><hr>");
Другие вопросы по тегам