dpbz14739 2017-03-20 21:34
浏览 50
已采纳

提交和/或重定向后重置表单输入

I have setup a contact form which is working nicely but I encountered two issues Im not able to solve.

First, I wonder if theres a good way to clear data which have been input by users in the form, for example after submit I want name/mail/message-fields to be cleared.

But the bigger problem is that with every submit or refresh the same info gets emailed and Ive read up on this and so far I only found the redirect way of solving this. To redirect to an other page after email sent (thankyou.php etc). If this is the ONLY way to solve this, well then the first issue is not a problem since I have to do this obviously. If so, how do I implement this?

Im trying to use if(!$mail->Send()) { header("Location: http://www.example.com"); exit; }

but im not able to get it to work, the page stays on same page but the form disappears. Mail still sent though.

In a perfect world, I would like to stay on same page, clear the fields and not be able to resend same data with refresh - but it seems like that is not possible?

If it isnt, here is my code - where should I use the header-redirect?

UPDATE

I managed to do it! This is in Wordpress btw.

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
";
    $headers .= "MIME-version: 1.0
";
    $headers .= "Content-type: text/html; charset=iso-8859-1
";
    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
}

Now, the only problem is that when sent/submitted, the page copies itself and I have the page as it were before + another full page (with header, menu, footer) beneath it. Why is this? Except that now mail is sent, fomr is cleared and refresh/new push on submit-button doesnt send another copy of the form as an mail - awesome!

Img: 2x header and footer

Thanks!

  • 写回答

3条回答 默认 最新

  • duaedf6509 2017-03-20 21:52
    关注

    UPDATE

    Good work learning the fundamentals of AJAX!

    In terms of handling ajax in wordpress specifically, there are some wordpress hooks for this:

    This article does a good job overviewing some of the fixes you will need to fine-tune this.

    The key to making your form work the wordpress way is to use the built in wordpress hooks, but they also suggest the following:

    Passing your ajax request to admin-ajax.php.

    Use jQuery to handle form submission.

    Applying a nonce field to protect the form processor script (you should do this no matter what).


    Don't forget to read up on the basics of PHP forms.

    The simplest thing to prevent form resubmission is to wrap your form validation code in a if(isset($_POST['submit']) condition.

    In terms of emptying the fields, you can do what the accepted answer here suggests: reset your $_POST variable after you've handled the form, or simply not echo out the $_POST data in your input values.

    The questions to ask regarding the use of AJAX are the following:

    Can you set up a separate file on your system to handle the php processing - but none of the html or javascript - of this form?

    Do you have access to a library such as jQuery to smooth the transition into using XHR?

    If so, you can make this form an ajax form that posts its data to your separate php file. That will ensure that only the javascript event you have chosen to trigger the form submission will run the php code. Plus it will give you all the fun animation stuff that javascript can handle and your no page reload goodness.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器