我的表格:
<form action="html_post.php" method="post" id="myform">
<textarea id="textarea" placeholder="Add your comment" name="posting"> </textarea>
<input class="button" type="button" name="send" value="Send">
</form>
我有这样的代码
$(".button").click(function () {
var content = $("#myform").serialize();
$.ajax({
url: "add_post.php",
type: "POST",
data: {
text: content,
action: "add_post"
},
success: function () {
$('#comment_block').load('list_post.php');
document.getElementById('textarea').value = "";
}
})
});
这样的php:
echo mysqli_error($connection);
if (strlen($_POST['posting']) >= 5) {
$text = htmlspecialchars($_POST['posting']);
$insert = "INSERT INTO post(content) VALUE ('$text')";
mysqli_query($connection, $insert);
}
但它不会向db添加文本。我只是在学习ajax,这是我第一次体验关键:价值所以你能帮助我吗?
是的,没有显示错误
答案 0 :(得分:1)
你写的方式没有$_POST['posting']
。相反,$_POST['text']
包含一个URL编码的字符串,其中包含表单中的所有输入,即"posting=blah blah blah"
之类的字符串。
你可能想要的是:
$(".button").click(function () {
var content = $("#myform").serialize();
$.ajax({
url: "add_post.php",
type: "POST",
data: content + '&action=add_post',
success: function () {
$('#comment_block').load('list_post.php');
document.getElementById('textarea').value = "";
}
})
});
答案 1 :(得分:0)
根据您发布的代码,在服务器上将在$ _POST变量中设置两个键。这些是您在javascript中的ajax请求中定义的:text
和action
。
因此,当您检查$_POST['posting']
时,它不存在,但有$_POST['text']
和$_POST['action']
。 $_POST['text']
将包含所有表单字段作为URL编码字符串,如"posting=xyz"
。为了访问这些值,您可以使用parse_str()
php函数来解析此字符串,因为它是一个查询字符串。
所以服务器端的情况可能如下所示。
if (isset($_POST['text'])) {
// $formdata passed in by reference, it will contain all the form fields
parse_str($_POST['text'], $formdata);
}
if (isset($formdata['posting']) && strlen($formdata['posting']) >= 5) {
// Perform db operation
}