[英]Jquery $.post() data cannot be retrieved as PHP variable
I am having a difficult time trying to make the Ajax request $.post() from Jquery work.我很难让 Ajax 请求 $.post() 从 Jquery 工作。 I would like to send data from a form with $.post() and retrieve it as php variables in order to further process them into an SQL database.我想使用 $.post() 从表单发送数据并将其检索为 php 变量,以便进一步将它们处理到 SQL 数据库中。
Below, I put a simplified version of my problem in a one page code (the Jquery posts to the same page when the function is triggered).下面,我将我的问题的简化版本放在一页代码中(当 function 被触发时,Jquery 发布到同一页面)。 I wish to use this method in order to not trigger a page reload when submitting the form.我希望使用此方法以在提交表单时不触发页面重新加载。
The problem : my post() function works, I get the correct alert stating the data posted, BUT , print_r($_POST) check method stays empty after I submit my request.问题:我的 post() function 有效,我收到正确的警报,说明发布的数据,但是,在我提交请求后,print_r($_POST) 检查方法保持为空。
My question : how can I get the posted data into php variables ($_POST['name'] & $_POST['email']?我的问题:如何将发布的数据放入 php 变量($_POST['name'] & $_POST['email']?
<!DoCType html>
<html lang="fr-CH">
<head>
<title> TEST </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="/JS/jquery-3.3.1.min.js"></script>
</head>
<body>
<?php
print_r($_POST); // always returns an empty array, even after clicking the submit button
if (isset($_POST['name'])) {
echo "PHP received data";
} else {
echo "It did not work";
}
?>
<div class='caseform'>
<form id="form" method="post">
Name:<br> <input type="text" name="name"> <br>
Email:<br> <input type="text" name="email"> <br>
<button id="button"> Submit </button>
</form>
</div>
<script>
$( document ).ready(function() {
$("#button").click(function( event ) {
event.preventDefault();
var postData = $('#form').serialize();
// the $.post goes to the same php file "test.php"
var jqxhr = $.post("test.php", postData ,function() {
}).done(function() {
// this works, I get an alert with postData from my form (name=&email=)
alert(postData);
}).fail(function() {
alert("Error submitting the form.");
})
});
});
</script>
</body>
</html>
The issue is you haven't got anything to prevent the post handling code from running for a GET request.问题是您没有任何东西可以阻止后处理代码为 GET 请求运行。 When you initially load the page it is a GET request, and it is running your print_r($_POST)
which of course is empty.当您最初加载页面时,它是一个 GET 请求,并且它正在运行您的print_r($_POST)
当然是空的。
Wrap that code in a check like this, and move it to the top of the file.将该代码包装在这样的检查中,并将其移动到文件的顶部。
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
print_r($_POST); // always returns an empty array, even after clicking the submit button
if (isset($_POST['name'])) {
echo "PHP received data";
} else {
echo "It did not work";
}
exit();
}
?><!DoCType html>
...
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.