简体   繁体   English

通过PHP将表单发送到邮件,而无需刷新页面和清除字段

[英]Send form to mail via PHP, without page refresh and fields cleared

I have a form on my website, which sends the information to my email via PHP code. 我的网站上有一个表格,该表格通过PHP代码将信息发送到我的电子邮件中。 It all works like a charm, though when I submit the form it refreshes/reloads the page. 尽管当我提交表单时,它都会刷新/重新加载页面,但这一切都像一个咒语。

Is there a way to make it so that when the user clicks the submit button that the page won't refresh and the fields will be cleared as well? 有没有一种方法可以使用户单击“提交”按钮时页面不会刷新,并且字段也将被清除?

I've been finding many posts by people with the same problem here on SO, though it's not all working for me. 我一直在这里找到很多有相同问题的人发布的帖子,尽管并不是所有帖子都对我有用。

What I already tried: using an iFrame. 我已经尝试过:使用iFrame。 The page then didn't refresh, and the fields wouldn't get cleared. 该页面然后没有刷新,并且这些字段也不会被清除。

What's the best thing for me to do? 对我来说最好的事情是什么?

HTML: HTML:

                <form class="contact-form" action="form.php" method="post">
                    <div class="row">
                        <div class="col-md-6">
                            <input type="text" name="name" placeholder="Naam" class="form-control" required>
                            <input type="email" name="email" placeholder="E-mail" class="form-control" required>
                            <input type="text" name="subject" placeholder="Onderwerp" class="form-control" required>
                        </div>
                        <div class="col-md-6">
                            <textarea type="text" name="message" placeholder="Bericht..." id="message" rows="25" cols="10" class="form-control" required></textarea>
                            <button type="submit" name="submit" class="btn btn-default submit-btn form_submit">VERSTUUR BERICHT</button>
                        </div>
                    </div>
                </form>

PHP: PHP:

if (isset($_POST["submit"])) {if (isset($_POST["submit"])) {
$nam = $_POST["name"];
$ema = $_POST["email"];
$sub = $_POST["subject"];
$mes = $_POST["message"];

$your_email = "testertje777@gmail.com";
$subject = $sub;
$email_body = $mes;

if (isset($_REQUEST['message'])) {
    mail ($your_email, $subject, $email_body, "From: $nam <$ema>");
    header ("Location: bomatec.be");
    exit();
}
}

Is there a way to make it so that when the user clicks the submit button that the page won't refresh and the fields will be cleared as well? 有没有一种方法可以使用户单击“提交”按钮时页面不会刷新,并且字段也将被清除?

There are multiple ways this can be achieved: 有多种方法可以实现:

iframe IFRAME

Like you mentioned, an <iframe> can be used as the target of the form. 就像您提到的, <iframe>可以用作表单的目标。 Ensure that the iframe has a name attribute defined, then use that value as the target value of the form. 确保iframe定义了名称属性,然后使用该值作为表单的目标值

<iframe name="ifr"></iframe>
<form class="contact-form" method="post" action="form.php" target="ifr">

In order to have the form fields cleared with the form is submitted, use a JavaScript handler, like the one below. 为了提交表单时清除表单字段,请使用JavaScript处理程序,如下所示。 The <script> tag would be added to the <body> tag (though it could go in the <head> tag but that could slow down page load). <script>标记将添加到<body>标记中(尽管它可以放在<head>标记中,但可能会减慢页面加载速度)。 When the DOM is ready, it will add a handler for form submission (using document.addEventListener() ). DOM准备就绪后,它将为表单提交添加处理程序(使用document.addEventListener() )。 When the handler is called, the form fields will be cleared via the call to HTMLFormElement.reset() . 调用处理程序时,将通过对HTMLFormElement.reset()的调用清除表单字段。

<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
    document.forms[0].addEventListener('submit', function(event) {
        event.target.reset();
    });
});
</script>

Note that this code presumes there is only one form on the page. 请注意,此代码假定页面上只有一种形式。 If there happen to be multiple then add an id attribute (eg <form id="maiForm"> ) and use that id attribute when accessing the form in JS (eg instead of document.forms[0] use document.getElementById('mailForm') ). 如果碰巧有多个,则添加一个id属性(例如<form id="maiForm"> )并在访问JS中的表单时使用该id属性(例如,代替document.forms[0]使用document.getElementById('mailForm') )。

See a demonstration of this technique in this phpfiddle . 此phpfiddle中查看此技术的演示。

AJAX (Javascript with XMLHttpRequest) AJAX(带有XMLHttpRequest的Javascript)

This is another technique similar to the iframe approach but instead it uses the Add a script tag like the one below to the <body> tag. 这是另一种与iframe方法类似的技术,但是它使用了将类似下面的脚本标签添加到<body>标签的方法。 It uses document.addEventListener() to wait for the DOM to be ready and then add an event handler for the form submission. 它使用document.addEventListener()等待DOM准备就绪,然后为表单提交添加事件处理程序。 That event handler will do the following: 该事件处理程序将执行以下操作:

  • Prevent the default form submission with Event.preventDefault() 使用Event.preventDefault()阻止默认表单提交
  • Serialize the form data by instantiating an instance of FormData 通过实例化FormData的实例来序列化表单数据
  • Send an asynchronous request using XMLHttpRequest.send() (ie AJAX) to the PHP page with the form data from the previous step as the POST data. 使用XMLHttpRequest.send() (即AJAX)将异步请求发送到PHP页面,并将上一步中的表单数据作为POST数据。
  • Resets the form using HTMLFormElement.reset() 使用HTMLFormElement.reset()重置表单

     <script type="text/javascript"> document.addEventListener('DOMContentLoaded', function() { document.forms[0].addEventListener('submit', function(event) { event.preventDefault(); var formData = new FormData(document.forms[0]); var xhr = new XMLHttpRequest(); xhr.open('POST', 'form.php', true); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { //request is done //request is finished - update DOM accordingly } } xhr.send(formData); document.forms[0].reset(); }); }); </script> 

See it demonstrated in this phpfiddle . 看到它在phpfiddle中得到了展示。 Notice that form.php has been replaced by <?php echo $_SERVER['PHP_SELF'];?> because there can only be one page in that fiddle environment. 注意, form.php已由<?php echo $_SERVER['PHP_SELF'];?>代替,因为在该小提琴环境中只能有一页。 Also the function mail() is disabled there so the lines containing that function have been commented out (and the l replaced by a 1 since the code won't run otherwise). 此外,函数mail()在那里也被禁用,因此包含该函数的行已被注释掉(并且l替换为1因为否则代码将无法运行)。

You can do it by AJAX function, for example via JQuery: 您可以通过AJAX函数来实现,例如通过JQuery:

$(".contact-form").submit(function() {
    return $.ajax({
        type: "POST",
        url: "form.php",
        data: $(this).serialize()
    }).done(function() {
            alert("Thanks for your message!"),
            $("form.contact-form").each(function() {
            this.reset();
        });
        })
});

Also you can remove action="form.php" from you HTML code. 您也可以从HTML代码中删除action="form.php" Please check jsfiddle for full example . 检查jsfiddle以获得完整示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM