簡體   English   中英

提交后用成功消息替換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。

我想要的是將表單替換為成功消息,以避免頁面刷新並避免彈出消息框。

來自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 "Your Message successfully sent, we will get back to you ASAP.";

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

首先,在頭元素中包含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>

首先,您應該使用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中實現起來也會非常容易。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM