如何在表单上执行php脚本后显示成功消息

时间:2017-07-22 15:27:58

标签: javascript php html css

所以我想标题就是这样,我有一个小的PHP脚本连接到一个输入表单。我想要的只是一个成功的页面,在用户提交电子邮件后会向用户显示一个链接。这应该很容易,但我对php来说很新。

无论如何,这里是php和html代码:

 <?php

  $visitor_email = $_POST['email'];

  $email_from = "LightDesigns";
  $email_subject = "Newsletter group";
  $email_body = "You have received a new person to add to the newsletter: 
  $visitor_email.\n".

  $to = "stefanvujic576@gmail.com";
  $headers = "From: $email_from \r\n";
  $headers .= "Reply-To: $visitor_email \r\n";
  mail($to,$email_subject,$email_body,$headers);
 ?>


 <section id="newsletter" style="margin-bottom: 0px;">
  <div class="container">
    <h1>Subscribe To My Newsletter</h1>

    <form action="email.php" method="POST" name="newsletterForm">
      <input class="emailBox_1" type="email" placeholder="Enter Email..." 
      name="email">
      <button class="button_1" type="submit" class="button_1">
      <span>Subscribe</span></button>
    </form>
 </div>

1 个答案:

答案 0 :(得分:1)

您只需要使用mail()结果并在视图中添加IF语句。此外,使用isset(),以便在打开页面时不会触发邮件,仅在电子邮件提交时触发。

<?php
    if (isset($_POST['email'])){
      $visitor_email = $_POST['email'];

      $email_from = "LightDesigns";
      $email_subject = "Newsletter group";
      $email_body = "You have received a new person to add to the newsletter: 
      $visitor_email.\n".

      $to = "stefanvujic576@gmail.com";
      $headers = "From: $email_from \r\n";
      $headers .= "Reply-To: $visitor_email \r\n";
      $result = mail($to,$email_subject,$email_body,$headers);
      // if ($result){
      // Redirect to success
      // header("location:success.php");
      // exit();
      // }
    }
?>


 <section id="newsletter" style="margin-bottom: 0px;">
  <div class="container">
    <h1>Subscribe To My Newsletter</h1>
    <?php
    if ($result){
        // Inline success
        echo "Success";
        // or
        // Include success
        // include("success.php");
        // or
        // redirect to success
        // echo "<meta http-equiv=\"refresh\" content=\"0;URL='success.php'\" />";  
    }else{
        ?>
            <form action="email.php" method="POST" name="newsletterForm">
              <input class="emailBox_1" type="email" placeholder="Enter Email..." 
              name="email">
              <button class="button_1" type="submit" class="button_1">
              <span>Subscribe</span></button>
            </form>
        <?php
    }
    ?>
 </div>

不是通过电子邮件向您发送要添加的电子邮件,为什么不将其添加到数据库?