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

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

最佳答案

您只需要使用 mail() 结果并在 View 中添加一个 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>

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

关于javascript - 如何在表单上执行 php 脚本后显示成功消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45256212/

相关文章:

javascript - React - 使用受控输入自动将博客文章保存到 sessionStorage()

javascript - 为什么将参数传递给 new Date() 会导致与不传递任何参数时不同的时区?

javascript - 如何验证 Grafana 图表并将其嵌入 iframe?

php - 如何在 Laravel 5.2 上安装 Socialite 2.0

javascript - onclick 事件不起作用

javascript - 使用具有特定 id 的 jquery 提交表单

JavaScript 参数无效?

php - 如何使用 php strftime 添加一天

html - 是什么造成了这种间距?

javascript - Firefox 不显示 Colorbox 照片