表单按钮在单击时刷新 - 单页网站



我创建了一个联系表单,以便用户可以向我们发送电子邮件。但是,每次我单击以发送电子邮件时,它也会在单击时刷新页面。这是一个单页网站。

我已经尝试了中建议的修复程序:如何使HTML按钮不重新加载页面

通过使用<button>元素或使用<input type="button"/>. 以及中建议的修复:单击表单内的按钮时防止刷新页面

通过添加onclick="return false;".

这两个修复程序都会阻止按钮在单击时刷新页面,但是,它也会阻止联系表单实际工作,并且不再向我们发送电子邮件。

我还更新了我的 PHP 以反映该类型的名称更改。

我的PHP是:

<?php
if(isset($_POST['submit'])){
$to = "example@example.com"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$name = $_POST['name'];
$subject = "Form submission";
$subject2 = "Copy of your form submission";
$message = $name . " wrote the following:" . "nn" . $_POST['message'];
$message2 = "Here is a copy of your message " . $name . "nn" . $_POST['message'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers);
mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
echo "Mail Sent. Thank you " . $name . ", we will contact you shortly.";
}
?>

我的HTML是:

<form action="" method="post" id="contactForm">
<input type="text" name="name" id="name" placeholder="Name...">
<input type="text" name="email" id="email" placeholder="Email...">
<p><br></p>
<textarea name="message" id="message" cols="40" rows="3" spellcheck="true" placeholder="Message..."></textarea>
<p><br></p>
<button type="submit" id="submit" name="submit" onclick="return false;">Send Message</button>
</form>

这目前适用于发送电子邮件,但不会阻止它刷新页面。将不胜感激任何关于它为什么要这样做的帮助。

编辑:

我已经使用 AJAX 尝试了几个不同的选项,因为有人建议这是最好的选择。所有这些都成功地阻止了页面刷新,但所有选项再次阻止了我的联系表单工作。我试过了:

1:

$(function() {
$('#contactForm').on('submit', function(e) {
$.post('index.php', $(this).serialize(), function (data) {
// This is executed when the call to mail.php was succesful.
// 'data' contains the response from the request
}).error(function() {
// This is executed when the call to mail.php failed.
});
e.preventDefault();
});
});

阿拉伯数字:

$("#contactForm").submit(function(e) {
e.preventDefault();
});

3:

我也尝试了Harsh Panchal提供给我的答案。

你可以尝试使用 jquery ajax 方法

为发送电子邮件和表单属性创建新文件以提供任何ID

<script>
$('#main-contact-form').submit(function(event){
event.preventDefault();
$.ajax({
type:'post',
url:'sendememail.php',
data:$(this).serialize(),
success:function(response){ 
if(response==1)
{   
setInterval(function(){$('.review_form').html('<h5><center><div class="alert alert-success">Review Successfully Submited......</div></center></h5>');},5);
}
else 
{
setInterval(function(){$('.review_form').html('<h5><center><div class="alert alert-danger">Sorry Your Review Not Submit......</div></center></h5>');},5);
}
}
});
});
</script>

@thickguru,如果您将邮件发送PHP代码与<form>...</form>保持在同一页面上,则不要期望收到有效的解决方案 - 无论是否使用ajax。即使页面不刷新,即使您使用的是 ajax,也必须从 ajax 结果重建页面(这是一个糟糕的选项)。因此,您必须在不同的页面中将这两个任务分开,并且只有在之后才使用 ajax。通过这种方式,您可以实现漂亮的"关注点分离"(请参阅关注点分离 - 至少第一段)。

下面是使用 ajax 提交表单的两个选项。

1. 使用"json"数据类型提交表单(推荐):

页面"send_mail.php":

注意:没有更多的if(isset($_POST['submit'])){...}。如果您使用此验证,它将失败,因为默认情况下,提交按钮不会作为 POST 变量的一部分发送。如果您仍希望验证 $_POST 数组,则必须手动将其分配为已发送data对象中的属性。

请注意 json 编码函数json_encode的使用。

<?php
$to = "example@example.com"; // this is your Email address
//...
$message = "Mail Sent. Thank you " . $name . ", we will contact you shortly.";
echo json_encode($message);
?>

页面"索引.html":

注意:submit按钮上没有onclick属性!

<div id="results"></div>
<form id="contactForm" name="contactForm" action="send_mail.php" method="post">
<!-- ... The form inputs ... -->
<button type="submit" id="submit" name="submit">Submit</button>
</form>

页面"index.js"(例如,带有js脚本的文件):

/**
* On document ready.
* 
* @return void
*/
$(document).ready(function () {
sendEmail();
});
/**
* Send email.
* 
* @return void
*/
function sendEmail() {
var contactForm = $('#contactForm');
var results = $('#results');
contactForm.submit(function (event) {
var ajax = $.ajax({
method: 'post',
dataType: 'json',
url: 'send_mail.php',
data: contactForm.serialize()
});
ajax.done(function (response, textStatus, jqXHR) {
results.html(response);
});
ajax.fail(function (jqXHR, textStatus, errorThrown) {
results.html('Email sending failed!');
});
ajax.always(function (response, textStatus, jqXHR) {
// ...
});
return false;
});
}

注意:如果您决定使用表单提交验证,则必须处理所有情况。例如,当您像这样使用它时,您将收到一个错误:

if (isset($_POST['submit'])) {
//...
$message = "Mail Sent. Thank you " . $name . ", we will contact you shortly.";
echo json_encode('Hello, World!');
}

解决方案是同时处理未设置的 POST "提交":

if (isset($_POST['submit'])) {
//...
$message = "Mail Sent. Thank you " . $name . ", we will contact you shortly.";
echo json_encode('Hello, World!');
} else {
echo json_encode('Submit button not recognized');
}

阿拉伯数字。使用"html"数据类型提交表单:

页面"send_mail.php":

注意:迪托。

<?php
$to = "example@example.com"; // this is your Email address
//...
$message = "Mail Sent. Thank you " . $name . ", we will contact you shortly.";
echo $message;
?>

页面"索引.html":

注意:迪托。

<div id="results"></div>
<form id="contactForm" name="contactForm" action="send_mail.php" method="post">
<!-- ... The form inputs ... -->
<button type="submit" id="submit" name="submit">Submit</button>
</form>

页面"索引.js":

/**
* On document ready.
* 
* @return void
*/
$(document).ready(function () {
sendEmail();
});
/**
* Send email.
* 
* @return void
*/
function sendEmail() {
var contactForm = $('#contactForm');
var results = $('#results');
contactForm.submit(function (event) {
var ajax = $.ajax({
method: 'post',
dataType: 'html',
url: 'send_mail.php',
data: contactForm.serialize()
});
ajax.done(function (response, textStatus, jqXHR) {
results.html(response);
});
ajax.fail(function (jqXHR, textStatus, errorThrown) {
results.html('Email sending failed!');
});
ajax.always(function (response, textStatus, jqXHR) {
// ...
});
return false;
});
}

我建议你不要使用postget的简写ajax版本。使用普通的 ajax 调用具有更大的灵活性。

祝你好运!

要在 ajax 中执行此操作,请删除form.action="",因为它将重新加载页面。

尝试

  • form中删除action属性。
  • button中删除type=submit
  • 将 Click 事件处理程序添加到button,而不是将其添加到form.submit

代码将如下所示

.HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form id="contactForm">
<input type="text" name="name" id="name" placeholder="Name...">
<input type="text" name="email" id="email" placeholder="Email...">
<p><br></p>
<textarea name="message" id="message" cols="40" rows="3" spellcheck="true" placeholder="Message..."></textarea>
<p><br></p>
<button id="submit" name="submit">Send Message</button>
</form>

jQuery

$(document).ready(function() {
$('#submit').click(function(e) {
e.preventDefault();
$.post('index.php', $("form#contactForm").serialize(), function(data) {}).error(function(xhr) {alert(xhr)});
});
});

使用 jQuery AJAX 表单提交并Event.preventDefault(),以便页面不会进一步刷新。

如需更多帮助,请访问链接 https://api.jquery.com/jquery.post/

我认为jQuery和AJAX是要走的路。我有几个建议:

  1. 尝试在执行$.post之前将e.preventDefault()移动到 。这应该会先停止事件,然后才能重新加载页面,然后发送电子邮件。

  2. 尝试在e.preventDefault()之外使用e.stopPropagation()或代替 。这将阻止事件冒泡 DOM,以便其他元素不会触发重新加载。

  3. 尝试在函数末尾添加return false;。这在哪里工作有一个类似的问题:阻止表单重定向或在提交时刷新?

最新更新