我正在尝试创建一个对我的php文件的ajax调用来插入数据。我遇到的问题是我发送的数据无法识别。
您将在php文件中看到的变量是无法识别的:
$home_comment = $_POST['home_comment'];
$username = $user->data()->username;
我正在运行一个ini文件,其中包含$con
连接,并且它始终具有$user
变量。
有人看到我做错了吗?
<form action="" method="POST" id="comment-form">
<label for="comment">Comment</label>
<textarea cols="15" id="home-comment" name="comment" placeholder="Message" rows="5" maxlength="1000" required></textarea><br>
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
<input id="comment-button" name="submit" type="submit" value="Post">
</form>
的Ajax:
$("#comment-form").on("submit", function (event) {
//event.preventDefault();
var home_comment = $("#home_comment").val();
$.ajax({
url: "comment-send.php",
type: "POST",
data: {
"home_comment": home_comment
},
success: function (data) {
// console.log(data); // data object will return the response when status code is 200
if (data == "Error!") {
alert("Unable to post comment!");
alert(data);
} else {
/*$("#newsletter-form")[0].reset();
$('.newsletter-popup').fadeIn(350).delay(2000).fadeOut();*/
}
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + " | " + errorThrown);
//console.log("error"); //otherwise error if status code is other than 200.
}
});
});
PHP文件:
$home_comment = $_POST['home_comment'];
$username = $user->data()->username;
$okay = true;
if ( $okay ) {
$comment_insert = "
INSERT INTO home_comments
(id, user_id, username, comment)
VALUES(?, ?, ?, ?)
";
$comment_stmt = $con->prepare($comment_insert);
$comment_stmt->execute(array('', $user_id, $username, $home_comment));
}
答案 0 :(得分:3)
检查一下:
此处 id:带连字符的主页评论
var home_comment = $("#home_comment").val();
在这里,您使用下划线
解决此问题并重试