【问题标题】:Resetting form input after submit and/or redirect提交和/或重定向后重置表单输入
【发布时间】:2017-08-12 08:48:51
【问题描述】:

我已经设置了一个运行良好的联系表,但我遇到了两个我无法解决的问题。

首先,我想知道是否有一个好的方法可以清除用户在表单中输入的数据,例如在提交后我希望清除姓名/邮件/消息字段。

但更大的问题是,每次提交或刷新时,都会通过电子邮件发送相同的信息,我已经阅读了这一点,到目前为止,我只找到了解决此问题的重定向方法。发送电子邮件后重定向到其他页面(thankyou.php 等)。如果这是解决这个问题的唯一方法,那么第一个问题不是问题,因为我必须这样做。如果是这样,我该如何实现?

我正在尝试使用if(!$mail->Send()) { header("Location: http://www.example.com"); exit; }

但我无法让它工作,页面保持在同一页面上但表单消失了。邮件仍然发送。

在一个完美的世界中,我想留在同一页面上,清除字段并且无法通过刷新重新发送相同的数据 - 但似乎这不可能?

如果不是,这是我的代码 - 我应该在哪里使用标头重定向?

更新

我成功了!顺便说一句,这是在 Wordpress 中。

HTML/contact.php:

<form id="contact-form" onsubmit="submitForm(); return false;"> <!--This calls submitForm(); and stops the form of doing anything else when submitted, prevents reloading-->
        <div class="contact-input">
          <input type="text" id="name" placeholder="Your name" required>
        </div>
        <div class="contact-input">
          <input type="email" id="mail" placeholder="Your mail" required>
        </div>
        <div class="contact-input">
          <textarea id="message" placeholder="Your message" rows="10" required></textarea>
        </div>
        <input id="submitButton" type="submit" value="Send"><span id="status"></span>
      </form>

JavaScript/contactform.js:

    function _(id) {
    return document.getElementById(id); //makes _ a shortcode for document.getElementById(id)
}

    function submitForm() {
            _("submitButton").disabled = true; //User cant click submit many times and resend form data, after first click its disabled.
            _("status").innerHTML = 'please wait...'; //Gives span value and the user an indication of that data is being processed.
            var formdata = new FormData(); // Creates variable that fetches they key value pair of id and value of  the form inputs.
            formdata.append( "name", _("name").value );
            formdata.append( "mail", _("mail").value );
            formdata.append( "message", _("message").value );
            var ajax = new XMLHttpRequest(); // creating an ajax variable which is a XMLHttpRequest, opens it/fires it by posting the formdata to parser.php
            ajax.open( "POST", "parser.php" );
            ajax.onreadystatechange = function() { //when ready do this function
                if(ajax.readyState == 4 && ajax.status == 200) { //when data is finished processing by php and data is returned by php to this ajax object(XMLHttpRequest)
                    if(ajax.responseText == "success") {
                    _("contact-form").innerHTML = '<h2>Thanks for contacting me '+_("name").value+' I will get back to you as soon as possible.</h2>'
                } else {
                _("status").innerHTML = ajax.responseText;
                _("submitButton").disabled = false; 
                clearForm();
                } 
            }
        }
        ajax.send( formdata );
    }

PHP/parser.php: (included_once in functions.php)

    <?php
if ( isset($_POST['name']) && isset($_POST['mail']) && isset($_POST['message']) ) {
    $name = $_POST['name'];
    $mail = $_POST['mail'];
    $message = nl2br($_POST['message']);
    $to = "kontakt@emcolsson.se";
    $from = $mail;
    $subject = 'Contact form message';
    $message = '<b>Name:</b> '.$name.' <br><b>Email:</b> '.$mail.' <p>'.$message.'</p>';
    $headers = "From: $from\n";
    $headers .= "MIME-version: 1.0\n";
    $headers .= "Content-type: text/html; charset=iso-8859-1\n";
    if( mail($to, $subject, $message, $headers) ) {
        echo "success";
    } else {
        echo "The server failed to send the message. Please try again later.";
    }
}
?>

JavaScript/clearform.js

function clearForm()
{
    document.getElementById("name").value=""; //don't forget to set the textbox ID
    document.getElementById("mail").value=""; //don't forget to set the textbox ID
    document.getElementById("message").value=""; //don't forget to set the textbox ID
}

现在,唯一的问题是,在发送/提交时,页面会自行复制,并且我拥有之前的页面 + 在其下方的另一个完整页面(带有页眉、菜单、页脚)。为什么是这样? 除了现在发送邮件之外,fomr 被清除并且提交按钮上的刷新/新推送不会将表单的另一个副本作为邮件发送 - 太棒了!

图片:2x header and footer

谢谢!

【问题讨论】:

  • 澄清一下,您想要的本质上是 ajax 表单的行为 - 提交、验证、服务器交付和清除表单 - 无需重新加载页面,对吗?
  • 嗨!你很快:) - 嗯,是的,但是页面是否重新加载不仅重要,如果这意味着它再次发送表单数据,在这种情况下是重复的电子邮件。我可以用ajax解决这一切吗?以前从未使用过,但如果是的话,我想学习它!
  • 是的,AJAX 是解决所有问题的好方法。不过,我仍然建议我在下面提到的将您的提交代码包装在 if(isset($_POST['submit']) 条件中。
  • 我真的做到了!生病更新帖子,因为还有一些问题!
  • 我相信wordpress有它自己的ajax hooks。

标签: php forms email redirect submit


【解决方案1】:

更新

学习 AJAX 的基础知识做得很好!

在 wordpress 中具体处理 ajax 方面,有一些 wordpress hooks 用于此:

This article 很好地概述了一些您需要微调的修复。

使您的表单以 wordpress 方式工作的关键是使用内置的 wordpress 钩子,但他们也建议以下内容:

将您的 ajax 请求传递给 admin-ajax.php。

使用 jQuery 处理表单提交。

应用 nonce 字段来保护表单处理器脚本(无论如何你都应该这样做)。


不要忘记阅读the basics of PHP forms

防止表单重新提交的最简单方法是将表单验证代码包装在if(isset($_POST['submit']) 条件中。

在清空字段方面,您可以执行accepted answer here 建议的操作:在处理完表单后重置$_POST 变量,或者干脆不在输入值中回显$_POST 数据。

关于使用 AJAX 的问题如下:

您能否在您的系统上设置一个单独的文件来处理这种表单的 php 处理 - 但没有 html 或 javascript -?

您是否可以访问诸如 jQuery 之类的库来顺利过渡到使用 XHR?

如果是这样,您可以将此表单设为 ajax 表单,将其数据发布到您单独的 php 文件中。这将确保只有您选择触发表单提交的 javascript 事件才会运行 php 代码。此外,它还将为您提供 javascript 可以处理的所有有趣的动画内容以及您的无页面重新加载优势。

【讨论】:

  • 好的,今天我会解决这个问题,不管需要多长时间。我从哪里开始?你有什么好的例子我可以看看 - 或者我应该只是谷歌 AJAX 表单并尝试模仿它直到它起作用?
【解决方案2】:

你有几个选择。您可以按特定 ID 清除字段。我用一个按钮来演示,但是你可以使用你的回调函数。如果您愿意,可以在小提琴中运行此代码。

<input id="inputs" type="text" value="hello world">
<button onclick="emptyInputs()">Empty</button>

<script>
function emptyInputs(){
document.getElementById('inputs').value="";
}
<script>

您还可以通过为要清除的输入分配一个类来清除它们。您必须遍历所有输入。注意我正在清除索引 [0]...您可以循环并清除它们。

document.getElementsByClassName('inputs')[0].setAttribute("value", "");

您也可以使用 Jquery 来执行此操作。

【讨论】:

    【解决方案3】:

    使用: 函数重定向($url,$status = 302){ header('位置:' . str_replace(array('&', "\n", "\r"), array('&', '', ''), $url), true, $status); 出口(); }

    【讨论】:

      猜你喜欢
      • 2013-04-13
      • 1970-01-01
      • 2021-09-29
      • 2015-12-28
      • 1970-01-01
      相关资源
      最近更新 更多