Javascript 提交后用成功消息替换 HTML 表单,表单使用单独的 php 文件发送邮件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33097135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:38:32  来源:igfitidea点击:

Replacing HTML form with success message after submit, form sends mail using separate php file

javascriptphphtmlforms

提问by Troy

I have an html contact form which is built into index.html, and then I have a mail.php file that sends a mail and also uses some Javascript. When I fill in form and submit, I have coded it to send the mail and then it pops up with a success message box and then redirects back to index.html.

我有一个内置于 index.html 的 html 联系表单,然后我有一个 mail.php 文件,它发送邮件并使用一些 Javascript。当我填写表单并提交时,我已经对其进行了编码以发送邮件,然后它会弹出一个成功消息框,然后重定向回 index.html。

What I would like is for the form to be replaced with the success message, to avoid a page refresh and also to avoid the popup message box.

我想要的是用成功消息替换表单,以避免页面刷新并避免弹出消息框。

form from index.html:

来自 index.html 的表单:

<form  action="mail.php" method="POST">
    <div class="row uniform">
    <div class="6u 12u$(xsmall)">
        <input type="text" name="name" id="name" value="" placeholder="Name" />
    </div>
    <div class="6u$ 12u$(xsmall)">
        <input type="email" name="email" id="email" value="" placeholder="Email" />
    </div>
    <div class="12u$">
        <!--<div class="select-wrapper">

        </div>-->
    </div>
    <div class="12u$">
        <textarea name="message" id="message" placeholder="Enter your message" rows="6"></textarea>
    </div>
        <center><div class="g-recaptcha" data-sitekey=""></div></center>
    <div class="12u$">
        <ul class="actions">
        <li><input type="submit" value="Send Message" class="special" /></li>
        <li><input type="reset" value="Reset" /></li>
        </ul>
    </div>
    </div>
</form>

php file, email address and recaptcha token removed for obvious reasons:

php 文件、电子邮件地址和 recaptcha 令牌因显而易见的原因被删除:

<?php $name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$formcontent = "From: $name \n email: $email \n Message: $message";
$recipient = 'email address here';
$subject = 'Message from Website';
$mailheader = "From: $email \r\n";
$captcha;
{
  if(isset($_POST['g-recaptcha-response']))
    {
      $captcha=$_POST['g-recaptcha-response'];
    }
  if(!$captcha)
    {
      echo '<script language="javascript">';
      echo 'alert("Please check the Captcha")';
      echo '</script>';
      exit;  
    }
  $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
  if($response.success==false)
  {
    echo '<h2>Please do not try and spam here.</h2>';
  }else
  {
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo '<script language="javascript">';
echo 'alert("Your Message successfully sent, we will get back to you ASAP.");';
echo 'window.location.href="index.html";';
echo '</script>';
  }
} ?>

This is a topic that I have actually looked at:

这是我实际看过的一个主题:

Clear form after submit and success message

提交和成功消息后清除表单

采纳答案by Sumit Pandey

Best way to do all your stuff is to use ajax. Include jquery in your html.

做所有事情的最好方法是使用ajax。在您的 html 中包含 jquery。

Put your form inside a wrapper div

将您的表单放在包装器 div 中

<div class="something">
<!-- your form here -->
</div>

Submit your form through ajax, instead of using basic form submission

通过ajax提交你的表单,而不是使用基本的表单提交

//"idform" is the id of the form
$("#idForm").submit(function() {

    var url = "path/to/your/script.php"; // the script where you handle the form input.

    $.ajax({
           type: "POST",
           url: url,
           // serialize your form's elements.
           data: $("#idForm").serialize(), 
           success: function(data)
           {
               // "something" is the class of your form wrapper
               $('.something').html(data);
           }
         });
    // avoid to execute the actual submit of the form.
    return false;
});

And last thing you need to change is in your php code

您需要更改的最后一件事是在您的 php 代码中

keep only one echo for success

只为成功留下一个回声

echo "Your Message successfully sent, we will get back to you ASAP.";

回答by kacper3w

First of all you should use AJAX call to submit the form. If you insist on using pure JS the script would look like this (written in 5 seconds - probably needs some adjusting):

首先,您应该使用 AJAX 调用来提交表单。如果您坚持使用纯 JS,脚本将如下所示(在 5 秒内编写 - 可能需要进行一些调整):

<script>

document.forms['yourForm'].onsubmit = function(form) { // you have to add 'name' attribute to the form and replace 'yourForm' with it
    var data = ... //here you have to get all the values from form elements and store them in data object. to make less changes to the script use the elements' names as object names
    if (window.XMLHttpRequest)
    {
        var xhReq = new XMLHttpRequest();
    }
    else
    {
        var xhReq = new ActiveXObject("Microsoft.XMLHTTP");
    }


    var method= 'POST')
    var async = false; //you can actually set true here, it doesn't matter much in this case
    var url = 'mail.php';
    xhReq.open(method, url, async);
    xhReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhReq.setRequestHeader("X-Requested-With", "XMLHttpRequest");
    xhReq.send(data);



    document.getElementById("form's parent's ID goes here").innerHTML = "new content"


    return false;
}
</script>

Than you have to remove all echos from php file as it wouldn't be shown anyway. You can also add some more sophistication to this script e.g. check if the mail function worked correctly (by returning something in php file and checking the AJAX response in JS) or to catch the captcha errors. It would also be extremely easier to achieve in jQuery if you're willing to go down that road.

比您必须从 php 文件中删除所有回声,因为它无论如何都不会显示。您还可以向该脚本添加一些更复杂的功能,例如检查邮件功能是否正常工作(通过在 php 文件中返回某些内容并在 JS 中检查 AJAX 响应)或捕获验证码错误。如果您愿意沿着这条路走下去,那么在 jQuery 中实现也将非常容易。

回答by DanielRead

You can accomplish this using jQuery and Ajax form submit.

您可以使用 jQuery 和 Ajax 表单提交来完成此操作。

First, include jquery in your head element

首先,在 head 元素中包含 jquery

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>

Next, give your form an id

接下来,给你的表单一个 id

<form  id='mail_form' action="mail.php" method="POST">

Add a span somewhere with the id='error'

在 id='error' 的某处添加一个跨度

<span id='error' style='color:red; font-weight:bold;'></span>

Adjust the mail.php to the following:

将 mail.php 调整为以下内容:

<?php 
$success = true;
$errors = array();

$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$formcontent = "From: $name \n email: $email \n Message: $message";
$recipient = 'email address here';
$subject = 'Message from Website';
$mailheader = "From: $email \r\n";
$captcha = false;

  if(isset($_POST['g-recaptcha-response']))
  {
      $captcha=$_POST['g-recaptcha-response'];
  }
  if(!$captcha)
  {
      $success = false;
      array_push($errors, "Please check the captcha");
  }
  $response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
  if($response.success==false)
  {
    $success = false;
    array_push($errors, "Please do not try and spam here.");

  }

if ($success)
{
    mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
}

$output_array = array("success" => $success, "errors" => $errors);
echo json_encode($output_array);
 ?>

Then, at the bottom of your page add

然后,在页面底部添加

<script>
$('#mail_form').on('submit', function(){
    var dataIn = $(this).serialize(); //serialize turns the form data into a string that can be passed to mail.php. Try doing alert(dataIn); to see what it holds.
    $.post( "./mail.php", dataIn )
        .done(function( dataOut )
        {
        //dataOut holds the response from mail.php. The response would be any html mail.php outputs. I typically echo out json encoded arrays as responses that you can parse here in the jQuery.
        var myArray = JSON.parse(dataOut );
        if (myArray['success'] == true) //Check if it was successfull.
            {
             $("#mail_form").html("Congrats! We just e-mailed you!");
            }
        else //there were errors
           { 
           $('#error').html(""); //Clear error span

            $.each(myArray['errors'], function(i){ 
            $('#error').append(myArray['errors'][i] + "<br>");
           }
        });
return false; //Make sure you do this or it will submit the form and redirect
});
</script>