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


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

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

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

form from 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文件,电子邮件地址和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>';
  }
} ?>

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

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

完成所有工作的最佳方法是使用ajax。在你的html中加入jquery。

将表单放入包装器div

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

通过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;
});
最后需要修改的是php代码

只保留一个echo for success

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

首先应该使用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>

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

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

首先,在head元素 中包含jquery
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
接下来,给你的表单一个id
<form  id='mail_form' action="mail.php" method="POST">

添加一个id='error'的span

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

将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);
 ?>

然后,在页面底部添加

<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>