提交 and/or 重定向后重置表单输入

Resetting form input after submit and/or redirect

我已经设置了一个工作正常的联系表格,但我遇到了两个我无法解决的问题。

首先,我想知道是否有一个很好的方法来清除用户在表单中输入的数据,例如提交后我希望name/mail/message-fields被清除。

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

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

但我无法使其正常工作,页面停留在同一页面上,但表单消失了。邮件仍然发送。

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

如果不是,这是我的代码 - 我应该在哪里使用 header-redirect?

更新

我做到了!这是在 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 在 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
}

现在,唯一的问题是,当 sent/submitted 时,页面会自行复制,而我的页面与之前一样 + 另一个完整页面(带有 header、菜单、页脚)在其下方.为什么是这样? 除了现在邮件已发送,表单已清除并且 refresh/new 推送 submit-button 不会将表单的另一个副本作为邮件发送 - 太棒了!

图片:2x header and footer

谢谢!

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

更新

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

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

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

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

正在将您的 ajax 请求传递给管理员-ajax.php。

使用jQuery处理表单提交。

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


别忘了阅读 the basics of PHP forms

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

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

关于使用 AJAX 的问题如下:

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

您是否可以访问 jQuery 等库来顺利过渡到使用 XHR?

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

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

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

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

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

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

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