我正在尝试将值传递给php文件。我收到提醒表单已提交,但没有显示在php文件中。我检查了js变量,它们正确显示。这是我的HTML表单。
<form name="sentMessage"role="form" data-toggle="validator" id="ContactForm" onsubmit="myFunction()">
<div class="form-group has-feedback">
<input type="text" pattern="^[_A-z ]{1,}$" class="form-control" placeholder="Your Name *" name="name" id="Username"
data-error="Plese enter your name" required>
<span class="glyphicon form-control-feedback" aria-hidden="true"></span>
<span class="help-block with-errors"></span>
</div>
<div class="form-group has-feedback">
<input type="email" class="form-control" placeholder="Your Email *" name="email" id="Useremail" required data-validation-required-message="Please enter your email address.">
<span class="glyphicon form-control-feedback" aria-hidden="true"></span>
<span class="help-block with-errors"></span>
</div>
<div class="form-group has-feedback">
<input type="tel" pattern="^[_0-9 ]{1,}$" class="form-control" placeholder="Your Phone *" name="phone" id="Userphone" required data-validation-required-message="Please enter your phone number.">
<span class="glyphicon form-control-feedback" aria-hidden="true"></span>
<span class="help-block with-errors"></span>
</div>
<div class="form-group">
<textarea class="form-control" placeholder="Your Message *" name="message" id="Usermesage" required data-validation-required-message="Please enter a message."></textarea>
<p class="help-block text-danger"></p>
<label class="light">
</div>
<button type="submit" class="btn btn-xl btn-success">
Send Message
</button>
</div>
</form>
<script>
function myFunction() {
var name = document.getElementById("Username").value;
var email = document.getElementById("Useremail").value;
var phone = document.getElementById("Userphone").value;
var message = document.getElementById("Usermesage").value;
$.ajax({
type: 'POST',
url: 'mailer.php',
data: {'name': name, 'email':email,'phone':phone,'message':message},
success: function(){
alert("The form was submitted");
}
});
}
</script>
PHP文件mailer.php
<?php
if($_POST){
echo $name = $_POST['name'];
echo $email = $_POST['email'];
echo $phone = $_POST['phone'];
echo $message = $_POST['message'];
}
?>
在php文件中没有显示任何内容。谢谢
答案 0 :(得分:1)
两个想法 - 您是通过普通表单提交表单,然后尝试通过AJAX调用提交相同的表单。这样就不会给AJAX调用提供任何值,因为它们已经被提交了 - 你可能需要阻止正常的表单提交 - 这里有很多答案可以帮助你阻止表单提交直到AJAX函数。
第二 - 我甚至会从表单中删除提交按钮,给它一个type =“button”属性并组合onclick事件处理程序和ajax调用(请注意我使用的是serialize()方法收集表单中的所有相关数据,而不是专门获取每个输入的值,而是: -
((lambda () (lambda (x) x)))