【问题标题】:Form Button Refreshes on Click - One page Website表单按钮在单击时刷新 - 一页网站
【发布时间】:2017-06-08 10:39:02
【问题描述】:

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

我尝试了以下建议的修复:How do I make an HTML button not reload the page

使用<button> 元素或<input type="button"/>。以及建议的修复:prevent refresh of page when button inside form clicked

通过添加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:" . "\n\n" . $_POST['message'];
   $message2 = "Here is a copy of your message " . $name . "\n\n" . $_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();
    });
});

2:

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

3:

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

【问题讨论】:

  • 你似乎在寻找的东西叫做 AJAX。
  • 啊!谢谢@FirstOne - 在您提出建议后刚刚对此进行了搜索,并有几个选项可供测试。欣赏评论。
  • @thickguru 请检查答案,如果您有任何问题,请告诉我
  • SagarV 我觉得投反对票和重复是因为您的答案未被接受。有点有趣 xD ......我没有用视频回复你,因为@aendeerei 有一个更好的答案。不知道为什么你也对他的回答投了反对票。咸的。
  • 我没有投反对票。这不是我这边的事情。骗子,我,有时访问旧帖子,我看到了那个。然后我想起了这个帖子。我检查了开放赏金是否存在。如果它存在,我可以将其标记为 mod 的唯一选项。但由于它不存在,我提出了一个欺骗标志。

标签: php html ajax forms


【解决方案1】:

你可以试试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>

【讨论】:

  • 恐怕这行不通。我设置了$('#contactForm') 并将URL 更改为index.php,因为这是一个单页网站。它只是完成了其他解决方案所做的事情,阻止它刷新页面,但也阻止了联系表单的工作。难道是因为它是一个单页网站导致了这个问题?
【解决方案2】:

@thickguru,如果您使用&lt;form&gt;...&lt;/form&gt; 在同一页面上维护您的邮件发送 php 代码,则不要期望收到有效的解决方案 - 有或没有 ajax。即使页面没有刷新,那么即使您使用 ajax,也必须从 ajax 结果重建页面(这是一个不好的选项)。因此,您必须将这两个任务分开在不同的页面中,然后才使用 ajax。通过这种方式,您可以实现漂亮的“关注点分离”(参见Separation of concerns - 至少是第一段)。

这里有两个使用 ajax 提交表单的选项。

1。使用“json”数据类型提交表单(推荐):

页面“send_mail.php”:

NOTA BENE:不再有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);
?>

页面“index.html”:

NOTA BENE: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 'submit':

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');
}

2。使用“html”数据类型提交表单:

页面“send_mail.php”:

NOTA BENE: 同上。

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

页面“index.html”:

NOTA BENE: 同上。

<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”:

/**
 * 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 调用,您可以获得更大的灵活性。

祝你好运!

【讨论】:

  • 感谢您的回答。我刚刚测试过了。它所做的是当我提交表单时,它实际上指向send_mail.php 页面。但是,联系表格可以工作,但现在会离开主页。
  • 因此,当我填写表单并选择提交时,页面不会像应有的那样停留在index.html,而是重定向到send_mail.php 并远离主页。
  • 可能问题出在响应类型上。我永远不会使用 html,我更喜欢 JSON 对象,然后将结果写入页面中的 html 对象或警报中。此外,如果您还遇到重新加载页面的问题,只需使用
  • @thickguru 感谢您的评论 ;-) 实际上,json 也应该适合您。最好使用它。而且我有一种感觉,在您的系统中,错误可以得到解决。我只是认为您在系统中某处的 json 调用之前正在打印或标头某些内容。所以,如果你想一劳永逸地解决这个问题,我现在就任你处置。
  • @thickguru 我扩展了我的答案以提供两个选项。注意事项:请勿在您的代码中使用自定义名称,例如“response”、“name”、“id”。在 js、html、php 或 mysql 中都没有。它很容易出错。因此,我不再使用 div 响应,而是再次使用“结果”。
【解决方案3】:

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

试试

  • form 中删除action 属性。
  • button 中删除type=submit
  • 将点击事件处理程序添加到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)});
  });
});

【讨论】:

  • 感谢赛格的回答。令人讨厌的是它没有用。它仍然允许我发送消息,这很好。但是当我单击提交按钮时,网页继续刷新。我复制了您建议的确切 HTML,并在表单上方的 &lt;script&gt; 标记中添加了 jQuery。
  • @thickguru 我做了一些小改动。请立即尝试。从form中删除post,添加event preventDefault,同样
  • 刚刚应用了新的更改。我害怕同样的问题。但是从form 中删除post 会阻止实际表单工作,并且不再发送电子邮件。
  • @thickguru 那是因为这个if(isset($_POST['submit'])){。将其更改为if(isset($_POST['name'])){
  • 完成后将我与 YouTube 链接一起发送出去。 @thickguru
【解决方案4】:

使用 jQuery AJAX 表单提交和Event.preventDefault(),这样页面就不会再刷新了。

更多帮助请点击链接https://api.jquery.com/jquery.post/

【讨论】:

  • 谢谢,会调查的。
【解决方案5】:

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

  1. 尝试将e.preventDefault() 移至$.post 之前。这应该会在事件重新加载页面并发送电子邮件之前停止该事件。

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

  3. 尝试在函数末尾添加return false;。有一个类似的问题在哪里有效:Prevent form redirect OR refresh on submit?

【讨论】:

    猜你喜欢
    • 2017-10-16
    • 1970-01-01
    • 2014-04-10
    • 1970-01-01
    • 2013-10-10
    • 2015-07-05
    • 1970-01-01
    • 2011-12-09
    • 1970-01-01
    相关资源
    最近更新 更多