[英]How to get php page to receive ajax post from html page
I have a very simple form that has an input field for first name.我有一个非常简单的表单,它有一个名字的输入字段。 I captured the form data and transmitted it via ajax to a PHP page using the standard jQuery posting method.
我捕获了表单数据并使用标准的 jQuery 发布方法通过 ajax 将其传输到 PHP 页面。 However, I am not able at all get any responses from the PHP page that any data was captured on the server-side.
但是,我根本无法从 PHP 页面获得任何响应,即在服务器端捕获了任何数据。 I am not sure what I have done wrong or what is missing.
我不确定我做错了什么或遗漏了什么。
Here is my code.这是我的代码。
Form:形式:
<form action="process.php" method="POST">
<div class="form-group">
<div class="form-row">
<div class="col-md-6 mb-3">
<label for="firstName">First name</label>
<input type="text" class="form-control" name="firstName" id="firstName" placeholder="First name">
<div class="d-none" id="firstName_feedback">
<p>Please enter a first name.</p>
</div>
</div>
</div>
</div>
<button class="btn btn-primary" type="submit">Submit form</button>
</form>
Here is my Jquery Ajax call:这是我的 Jquery Ajax 调用:
<script>
$(document).ready(function() {
$('form').submit(function(event) {
var formData = $("form").serialize();
console.log(formData);
$.ajax({
type: 'POST',
url: 'form.php',
data: formData,
dataType: 'json',
encode: true
})
.done(function(data) {
console.log(data);
});
event.preventDefault();
});
});
</script>
And here is my PHP page:这是我的 PHP 页面:
if(isset($_POST['formData']))
$ajaxData = ($_POST['formData']);
echo $ajaxData;
{
}
In your Ajax function, you're passing the contents of formData
to the server, though not as formData
but as their original input name.在您的 Ajax 函数中,您将
formData
的内容formData
给服务器,尽管不是作为formData
而是作为它们的原始输入名称。
In this case, you have:在这种情况下,您有:
<input type="text" class="form-control" name="firstName" id="firstName" placeholder="First name">
The input's name is firstName, so you need to call $_POST['firstName']
instead of $_POST['formData']
.输入的名称是 firstName,因此您需要调用
$_POST['firstName']
而不是$_POST['formData']
。
if (isset($_POST['firstName'])) {
$ajaxData = $_POST['firstName'];
echo $ajaxData;
}
The same applies for any other field you would have in your form, so for example, having another input with the name lastName
means you'd have to call $_POST['lastName']
to access it.这同样适用于表单中的任何其他字段,例如,具有名称为
lastName
另一个输入意味着您必须调用$_POST['lastName']
来访问它。
There were also some misplaced brackets and parentheses in the PHP code which I accommodated above.我上面提到的 PHP 代码中也有一些错位的方括号和圆括号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.