2014-11-03 34 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));