我有一个内置于index.html 中的html 联系表单,然后我有一个mail.php 文件,用于发送邮件并使用一些Javascript。当我填写表单并提交时,我已对其进行编码以发送邮件,然后弹出一个成功消息框,然后重定向回index.html。
我想要的是用成功消息替换表单,以避免页面刷新并避免弹出消息框。
来自index.html的表单:
<form action="mail.php" method="POST">
<div class="row uniform">
<div class="6u 12u$(xsmall)">
<input type="text" name="name" id="name" value="" placeholder="Name" />
</div>
<div class="6u$ 12u$(xsmall)">
<input type="email" name="email" id="email" value="" placeholder="Email" />
</div>
<div class="12u$">
<!--<div class="select-wrapper">
</div>-->
</div>
<div class="12u$">
<textarea name="message" id="message" placeholder="Enter your message" rows="6"></textarea>
</div>
<center><div class="g-recaptcha" data-sitekey=""></div></center>
<div class="12u$">
<ul class="actions">
<li><input type="submit" value="Send Message" class="special" /></li>
<li><input type="reset" value="Reset" /></li>
</ul>
</div>
</div>
</form>
由于显而易见的原因,删除了 php 文件、电子邮件地址和 recaptcha 令牌:
<?php $name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$formcontent = "From: $name \n email: $email \n Message: $message";
$recipient = 'email address here';
$subject = 'Message from Website';
$mailheader = "From: $email \r\n";
$captcha;
{
if(isset($_POST['g-recaptcha-response']))
{
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha)
{
echo '<script language="javascript">';
echo 'alert("Please check the Captcha")';
echo '</script>';
exit;
}
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
if($response.success==false)
{
echo '<h2>Please do not try and spam here.</h2>';
}else
{
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo '<script language="javascript">';
echo 'alert("Your Message successfully sent, we will get back to you ASAP.");';
echo 'window.location.href="index.html";';
echo '</script>';
}
} ?>
这是我实际研究过的一个主题:
提交后清除表单并显示成功消息 https://stackoverflow.com/questions/30935579/clear-form-after-submit-and-success-message
完成所有工作的最佳方法是使用 ajax。在你的 html 中包含 jquery。
将您的表单放入包装 div 中
<div class="something">
<!-- your form here -->
</div>
通过 ajax 提交表单,而不是使用基本表单提交
//"idform" is the id of the form
$("#idForm").submit(function() {
var url = "path/to/your/script.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
// serialize your form's elements.
data: $("#idForm").serialize(),
success: function(data)
{
// "something" is the class of your form wrapper
$('.something').html(data);
}
});
// avoid to execute the actual submit of the form.
return false;
});
最后需要更改的是 php 代码
只保留一个回声就成功
echo "Your Message successfully sent, we will get back to you ASAP.";
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)