使用AJAX

时间:2017-04-14 00:30:26

标签: php ajax

我正在建立一个论坛网站,但我无法弄清楚为什么我的AJAX代码无法正常工作。问题是: 我通过while循环为用户制作的每个帖子生成多个表单(评论部分),并且我编写了以下AJAX脚本:

<script type="text/javascript">

$(document).ready(function()
{
    $(".comment_submit2").click(function(){
        var topic_id = <?php echo $_GET['id']; ?>;
        var post_id = // receiving the id from the form
        $.ajax({
            type: "POST",
            url: "comment_on_post.php",
            data: {topic_id: topic_id,post_id : post_id,comment : $('textarea#commenting2').val() }, //success on the first post only
            //data: $(this).serialize(), not working at all..
            cache: false,
            success: function(data){
                alert(data);
                location.replace("topic2.php?id=<?php echo $_GET['id']; ?>");
            }
        });
        return false;
    });
});

</script>

<?php

include 'dbh.php';
//some other stuff...
$result_posts = $conn -> prepare("SELECT * FROM posts WHERE post_topic=:post_topic ORDER BY DATE(post_date) ASC");
$result_posts -> bindParam(':post_topic',$topic_id);
$result_posts -> execute();
while ($row2 = $result_posts ->fetch(PDO::FETCH_ASSOC)) 
{
    ?>
    //some other stuff...
    <form name="form2" id=" <?php echo $row2['post_id']; ?> ">
      <textarea id="commenting2" placeholder="Leave a comment" cols="30"rows="5"></textarea>
      <br>
      <input type="submit" class="comment_submit2" value="Comment">
    </form>
    //I need to pass the value id of form to ajax
    //some other stuff...
<?php  } ?>

“comment_on_post.php”文件如下:

<?php

include 'dbh.php'; 
session_start();

if (isset($_SESSION['uid'])) {
    $user     = $_SESSION['uid'];
    $reply    = $_POST['comment'];
    $topic_id = $_POST['topic_id'];
    //$post_id  = ?
    $comments = $conn -> prepare("INSERT INTO comments (uid,topic_id,post_id,comment,date) VALUES (:uid,:topic_id,:post_id,:reply,NOW())"); 
    $comments -> bindParam(':uid',$user);
    $comments -> bindParam(':topic_id',$topic_id);
    $comments -> bindParam(':post_id',$topic_id);
    $comments -> bindParam(':reply',$reply);
    $comments -> execute(); 
}

?>

此代码仅适用于第一篇文章。我试过serialize(),但我觉得我做错了。有没有人有想法解决这个问题?

1 个答案:

答案 0 :(得分:1)

ID必须是唯一的,$('textarea#commenting2')将获取具有该ID的第一个文本区域的内容,而不是当前表单中的内容。您应该使用class="commenting2"而不是ID,然后使用DOM遍历来查找当前表单中的textarea。

data: {topic_id: topic_id, post_id: this.form.id ,comment : $(this).siblings('textarea.commenting2').val() },