【问题标题】:Replacing HTML form with success message after submit, form sends mail using separate php file提交后用成功消息替换 HTML 表单,表单使用单独的 php 文件发送邮件
【发布时间】:2016-01-10 21:03:16
【问题描述】:

我有一个内置在 index.html 中的 html 联系表单,然后我有一个 mail.php 文件,它可以发送邮件并使用一些 Javascript。当我填写表单并提交时,我已经对其进行了编码以发送邮件,然后它会弹出一个成功消息框,然后重定向回 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 文件、电子邮件地址和 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>';
  }
} ?>

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

Clear form after submit and success message

【问题讨论】:

    标签: javascript php html forms


    【解决方案1】:

    完成所有工作的最佳方式是使用 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 "Your Message successfully sent, we will get back to you ASAP.";
    

    【讨论】:

    • 仅供参考:data.message 将未定义,data 本身将是一个字符串 — "Your Message successfully sent, we will get back to you ASAP."
    • 哎呀..我以为我要返回一个格式化的 json...谢谢,我会更新我的答案。
    • @SumitPandey 我有兴趣尝试您的答案,我实现了 hunijkah 提交的答案,但错误检查出现错误,我一直在查看问题是什么,但是我是 Ajax 和 jquery 的新手。我的 php 文件已经检查了所有的错误,所以我认为 php 文件仍然可以处理。你的回答能解决我的问题吗?我非常接近完成这项工作,但错误检查实际上是唯一的障碍,如果表格填写正确,它会完美运行。
    • @Troy: 嘿,如果你想使用 hunijkah 方法......只需一个改变...... array_push 是一个函数而不是一个变量。所以你必须在 mail.php 中将 $array_push 更改为 array_push
    • @SumitPandey 我现在实际上尝试了您的方法,并且效果很好,正是我想要的方式。非常感谢!
    【解决方案2】:

    首先你应该使用 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 响应)或捕获验证码错误。如果您愿意走这条路,那么在 jQuery 中实现也将非常容易。

    【讨论】:

    • 原生 xhr req 加 1。
    【解决方案3】:

    您可以使用 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 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>
    

    【讨论】:

    • 所以我使用了您的解决方案,它确实有效。但是,我的错误检查不再起作用了,即我只填写了姓名和一条消息而没有填写电子邮件或勾选recaptcha,它仍然带有一条成功消息,我应该怎么做才能确保我仍然得到相同的错误检查我是否像以前使用我的 php 文件一样?
    • @Troy 更改为:success,并添加.fail,您将能够根据服务器响应相应地输出。 api.jquery.com/jquery.ajax
    • @Troy 我刚刚更新了我的答案,包括错误检查我在 JSON 数组评论中解释的方式
    • @hunijkah 所以我做了你说的所有更改,当我填写所有字段并勾选验证码时,消息正确出现,然后我收到邮件。然后我尝试将电子邮件部分留空并勾选验证码,它出现了致命错误:“函数名称必须是第 21 行 /mail.php 中的字符串”所以我猜它没有正确捕获错误,在另一个在这种情况下,我没有勾选验证码,它显示了成功消息,但实际上并没有发送电子邮件。很抱歉需要被灌输所有这些,我更像是一名 C# 程序员,但我正在从这一切中学习。
    • @hunijkah:嘿,array_push 是一个函数而不是变量。所以你必须在 mail.php 中将 $array_push 更改为 array_push
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-07
    • 2017-11-17
    • 2015-11-18
    • 1970-01-01
    • 1970-01-01
    • 2011-09-01
    • 1970-01-01
    相关资源
    最近更新 更多