表单提交后如何留在同一页面上?

时间:2020-05-18 09:57:39

标签: php html

我有一个简单的PHP问题。

我有一个文本框,用户可以在其中输入电子邮件并提交成为我们邮件列表的一部分。现在,文本框位于页脚的每个页面上。我遇到的问题是,它一直试图将我重新定位到marketing-email.php(在其中处理所有表单提交的php发生了。)我希望该位置保留在用户所在的当前页面上。下面的代码:

header("Location: $_SERVER['HTTP_REFERER']?mailingsent=1");
die;

但是仍然需要我进入marketing-email.php。加上它给了我意外EOF的语法错误。

如何使它起作用,以便在提交后,它仍停留在当前页面上,而最后只添加了一个参数?

以下代码:

footer.php

<?php
$mailingsent=0;
if (isset($_GET['mailingsent'])) {
     $_GET['mailingsent'];
}
?>
<html>
<body>

...


        <section id="marketing-email">
        <form class="marketing-email-form" method="post" action="https://test.com/marketing-email.php">
        <div>
        <label for="email"><b>Stay updated on any new courses and services we have to offer by joining our mailing list</b></label><br/>
        <input type="email" id="market-email" name="market-email" required placeholder="Email"/> 
        <button type="submit" class="marketing-btn">Send</button>
        </div>
            </form>
       </section>

       <?
  if (isset($_GET['mailingsent'])) {
    echo '    <section id="mailing_list_email_sent" style="background-color:green !important;width:100%;">
        <div class="container">
            <div class="row">
                <div class="col-md-12">
                    <p class="tagline-content">
                        Email successfully sent to our mailing list!
                        <span class="closemailinglistemailmsg" 
                        style="color:white; 
                        font-size:1.5em;
                        float:right;">&times;</span>
                    </p>
                </div>
            </div>
        </div>
  </section>';
}
?>

...

        <script>

        // Get the modal
var modal = document.getElementById("mailing_list_email_sent");

// Get the <span> element that closes the modal
var spanMailingList = document.getElementsByClassName("closemailinglistemailmsg")[0];

// When the user clicks on <span> (x), close the modal
spanMailingList.onclick = function() {
  modal.style.display = "none";
}

    </script>

marketing-email.php

<?php
$errors = '';
if(
   empty($_POST['market-email']
   ))
{
    $errors .= "\n Error: email is required";
}

$email_address = $_POST['market-email'];

if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email_address))
{
    $errors .= "\n Error: Invalid email address";
}

if( empty($errors))
{
$email_body = "Request to join mailing list: $email_address";

$email_subject = "Mailing List Metis - $email_address";
mail("test@test.com",$email_subject,$email_body);


header("Location: $_SERVER['HTTP_REFERER']?mailingsent=1");
die;
}
?>

1 个答案:

答案 0 :(得分:0)

您可以将其作为函数并将其包含在文件中以供提交...

marketing-email.php

例如:函数submitHandleter($ data){

并编写所有逻辑 }

在footer.php

关于您的表格包括(marketing-email.php);

并调用函数

if(isset($_POST['market-email'])){
submitHandleter($_POST);

}

并在同一页面上保留表单操作