以ajax评论表格中的帖子参数

时间:2016-03-30 11:29:20

标签: php jquery ajax

我试图从我购买的模板中自定义一个评论表单。简而言之,我有3个文件 - post.phpcomment_post.phpmain.js。在post.php中是简单的html评论表单。我在ajax部分并没有那么好,仍然在尝试学习php,所以我需要一些帮助。

<form class="row" role="form" id="comments-form" name="comments-form" action="comments-send.php" method="POST">
        <input type="text" class="form-control form-name-error" name="comments[form-name]" id="form-name" placeholder="Name">
        <input type="email" class="form-control form-email-error" id="form-email" name="comments[form-email]" placeholder="Email">                          
        <input type="hidden" name="comments[post_id]" value="<?php echo $row['post_id'];?>" >
        <textarea class="form-control input-row-2 form-review-error" rows="3" id="form-comments" name="comments[form-review]" placeholder="Comment"></textarea>
        <div class="form-group text-right btn-submit">
            <button type="submit" class="btn btn-dark button-submit">Send</button>
            <div class="message-success alert-success alert hidden" style="position: absolute"><i class="fa fa-check"></i></div>
         </div> 
</form>

我有一个隐藏的字段来获取post_id .. 这是comment_post.php这是问题(我认为)。错误为Undefined variable: comment_author_name, comment_author_image .. etc

if(isset($_POST['comments'])) {

$response = array('status' => '', 'errors'=>array());

foreach($_POST['comments'] as $key => $value) {
    if($value == '') {
        $response['errors'][$key.'-error'] = 'error'; 
    }
}
if(empty($response['errors'])) {

    $_POST['comments']['form-name'] = $comment_author_name;
    $_POST['comments']['form-email'] = $comment_author_email;
    $_POST['comments']['post_id'] = $post_id;
    $_POST['comments']['form-review'] = $comment_text;

    $sql = "INSERT INTO comments (comment_author_name, comment_author_email, comment_date, comment_text, post_id) 
            VALUES (:comment_author_name, :comment_author_email, NOW(), :comment_text, :post_id)";
        $stmt = $pdo->prepare($sql);

        $stmt->bindValue(":comment_author_name", $comment_author_name);
        $stmt->bindValue(":comment_author_email", $comment_author_email);
        $stmt->bindValue(":post_id", $post_id);  
        $stmt->bindValue(":comment_text", $comment_text);

    $stmt->execute();       


    $response['status'] = 'ok';
} else {
    $response['status'] = 'error';
}
echo json_encode($response);
}

在原始文件(comment_post.php)中没有数据库插入,这是我的代码。我不确定如何在发送到php部分时从表单中获取值。这来自main.js的{​​{1}}文件。

comment_form

1 个答案:

答案 0 :(得分:1)

看起来您没有正确设置变量

更新到此

$comment_author_name = $_POST['comments']['form-name'];
$comment_author_email = $_POST['comments']['form-email'];
$post_id = $_POST['comments']['post_id'];
$comment_text = $_POST['comments']['form-review'];

您要做的实际上是从$ _POST获取值并将它们保存到您创建的变量中。

之前您正在进行对话,因此变量不存在,您也在重置$ _POST中的值