Javascript ajax注释表单未将数据发布到mysql
我正在使用ajax向mysql表发布注释。当我发表评论时,javascript正在加载,但它没有将数据提交到mysql数据库Javascript ajax注释表单未将数据发布到mysql,javascript,php,mysql,ajax,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', succ
$(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
您在html表单中遇到问题,您在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>
试着调试代码,这样你就可以知道你到底遇到了什么问题。有错误吗?检查你的“网络”选项卡,查看服务器端代码失败的原因值(:id,:comment,:username);
分号没问题,只需做一些简单的调试,检查PHP上的var\u dump($\u POST)
和console.log(响应)
关于ajax的成功块。别忘了打开错误报告查看浏览器的开发工具。查看JavaScript控制台。它是否报告任何错误?查看Net选项卡。是否发出请求?是否得到响应?它们是否包含您期望的数据?
<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>
$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));