2014-11-03 30 views
-2

我使用ajax发表评论到mysql表。当我发布评论时,javascript正在加载,但它不会将数据提交给mysql数据库。ajax评论形式不发布数据到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> 
+0

尝试调试代码,所以你可能会知道你得到了什么确切的问题 – Ricky 2014-11-03 06:14:08

+1

是否有错误?检查您的网络选项卡,看看为什么服务器端代码不合格 – 2014-11-03 06:14:10

+1

'VALUES(:id,:comment,:username);'< - 为什么在这里有分号 – Ohgodwhy 2014-11-03 06:17:28

回答

0

您在HTML形式的问题,你已经使用了多个"各地引起打破value属性PHP变量,使用更新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));