我是Php和Ajax的新手,我一直在讨论这个问题。我尝试使用$.post
简写函数使用ajax更新我的简单表单,但我的脚本不会返回任何内容。我也试过了$.ajax
,并使用了不同的数据类型,如json对象,json变量,serialize()
等。
HTML
<section class="contact" id="contact">
<h2>Do you have a project in mind? Let's discuss it</h2>
<div id="form-messages">
</div>
<form action="" method="post" id="contact-form">
<div class="row">
<div class="col span-1-of-4"><label for="name">Your name</label></div>
<div class="col span-3-of-4"><input type="text" name="name" id="name" placeholder="Enter your name ..."></div>
</div>
<div class="row">
<div class="col span-1-of-4"><label for="email">Your email</label></div>
<div class="col span-3-of-4"><input type="email" name="email" id="email" placeholder="Enter your email ..."></div>
</div>
<div class="row">
<div class="col span-1-of-4"><label for="message">Your message</label></div>
<div class="col span-3-of-4"><textarea name="message" id="message" placeholder="Type in your message ..."></textarea></div>
</div>
<div class="row">
<div class="col span-1-of-4"></div>
<div class="col span-3-of-4"><input type="submit" name="submit" id="submit" value="Send your message"></div>
</div>
</form>
</section>
PHP
<?php
$name= $_POST['name'];
$email= $_POST['email'];
$message= $_POST['message'];
$error="";
$result="";
if (isset($_POST["submit"])) {
if (!$name) {
$error="<br />Please enter your name";
}
if (!$email) {
$error.="<br />Please enter your email address";
}
if (!$message) {
$error.="<br />Please enter a message";
}
if ($_POST['email']!="" AND !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$error.="<br />Please enter a valid email address";
}
if ($error) {
$result='<div class="error-message"><p id="alert"><strong>There were error(s) in your form:</strong>'.$error.'</p></div>';
} else {
if (mail("abderrahim.gadmy@gmail.com", "Gadmy Visions: Someone sent you a message!",
"Name: ". $_POST['name']."
Email: ".$_POST['email']."
Comment: ".$_POST['message'])) {
$result='<div class="success-message"><p id="alert"><strong>Thank you!</strong> I\'ll be in touch</p></div>';
} else {
$result='<div class="error-message"><p id="alert">Sorry, there was an error sending your message. Please try again later.</p></div>';
}
}
echo $result;
}
?>
JS
$(document).ready(function(){
$('#contact-form').on('submit',function(event){
$.post('contact.php',$('form').serialize(), function(data){
$('#form-messages').html(data);
});
//Prevent refresh
event.preventDefault();
});
});
答案 0 :(得分:1)
长话短说:
jQuery serialize()不会序列化按钮(因为它不知道用于提交表单的按钮)。请参阅:Link以及jQuery serialize documentation:
注意:只有&#34;成功控制&#34;被序列化为字符串。没有提交按钮值被序列化,因为表单未使用按钮提交。
由于您的PHP-File仅在设置了$_POST["submit"]
时才生成输出(由于它未与表单的其余部分一起序列化,因此不是这种情况)实际上没有返回任何内容。< / p>
在php文件中使用不同的条件来检查表单是否实际成功发布,或者手动将提交按钮附加到序列化数据。
答案 1 :(得分:0)
尝试使用
检查表单是否可以提交if($ _ SERVER [&#39; REQUEST_METHOD&#39;] ==&#34; POST&#34;)而不是使用isset($ _ POST [&#34; submit&#34;]))。