ajax评论表没有将数据发布到mysql

时间:2014-11-03 06:09:43

标签: javascript php mysql ajax

我正在使用ajax将注释发布到mysql表。当我发布评论时,javascript正在加载,但它不会将数据提交到mysql数据库。

$(document).ready(function(){
   $('#commentform').on('submit',function(e) {
      $.ajax({
         url:'ajax.php',
         data:$(this).serialize(),
         type:'POST',
         success:function(data){
            console.log(data);
            $("#success").show().fadeOut(5000);
         },
         error:function(data){
            $("#error").show().fadeOut(5000);
         }
      });

      e.preventDefault();
   });
});

ajax.php

$id =   $_POST['id'];
$comment    =   $_POST['comment'];
$username   =   $_POST['username'];

$array = $pdo->prepare("INSERT INTO `comments` (id, comment, user)
VALUES (:id,:comment,:username);");
$array->execute(array(':id' => $id, ':comment' => $comment, ':username' => $username));

HTML

<form method="post" name="commentform" id="commentform">
   <textarea name="comment" name="comment"></textarea><br>
   <input type="hidden" value="<?php echo "$id"; ?>" name="id" id="id" />
   <input type="hidden" value="<?php echo "$username"; ?>" name="username" id="username" />
   <input type="submit" name="submit" id="submit" value="REPLY" />
</form>

1 个答案:

答案 0 :(得分:0)

你有html格式的问题,你使用了多个"围绕php变量导致破坏value属性,使用更新的html

<强> HTML

<form method="post" name="commentform" id="commentform">
   <textarea name="comment" name="comment">test comment</textarea><br>
   <input type="hidden" value="<?php echo $id; ?>" name="id" id="id" />
   <input type="hidden" value="<?php echo $username; ?>" name="username" id="username" />
   <input type="submit" name="submit" id="submit" value="REPLY" />
</form>

Ajax脚本没问题

这里是fiddle,这使得ajax请求正常

ajax.php 看起来也不错

$id =   $_POST['id'];
$comment    =   $_POST['comment'];
$username   =   $_POST['username'];

$array = $pdo->prepare("INSERT INTO `comments` 
            (id, comment, user) 
                VALUES 
            (:id, :comment, :username)"
         );

$array->execute(array(
            ':id' => $id, 
            ':comment' => $comment, 
            ':username' => $username));