PHP 合同表格,消息已发送

PHP contract form, Message Sent

我制作了一个 PHP 联系表,它向我发送了一封电子邮件。 并通知用户刷新页面后消息已发送。

我只能在刷新页面之前弹出,问题是如果用户在单击确定之前离开页面,则不会发送消息。

这是我当前的代码:

<?php
if(isset($_POST['submit'])){
    $name = $_POST['name'];
    $subject=$_POST['subject'];
    $mailFrom=$_POST['mail'];
    $message=$_POST['message'];

    $mailTo = "something@something.org";
    $headers = "From: ".$mailFrom;
    $txt ="You have received an e-mail from".$name.".\n\n" .$message;


    if ($name != '' && $mailFrom != '') {
        if (mail ($mailTo, $subject, $message, $mailFrom)) {
            echo '<p>Your message has been sent.</p>';
        } else { 
            echo '<p>Something went wrong, go back and try again.</p>'; 
        }
    }  else {
        echo '<p>You need to fill in all required fields.</p>';
    }
}

mail($mailTo,$subject,$txt,$headers);
header("Location: index.php") ;


?>

HTML:

<div class="modal-bg">
                <div class="modal">
                    
                    <form class="contact-form" action="contactform.php" method="post">
                    <h2>Contact Us!</h2>
                    <label for="name">Name: </label> </br>
                    <input type="text" name="name" placeholder="Your name"> </br>
                    <label for="email">E-mail</label> </br>
                    <input type="text" name="mail" placeholder="Your e-mail"> </br>
                    <label for="subject">Subject:   </label> </br>
                    <input type="text" name="subject" placeholder="Subject"> </br>
                    <label for="message">Message:   </label> </br>
                    <textarea name="message" class="message" placeholder="Message"  rows="15" cols="50"></textarea> </br>
                    <button type="submit" name="submit"> SEND </button>
                </form>
                    <span class="modal-close">X</span>
                </div>
            </div>

好的,所以你所拥有的是我过去遇到的问题:你正在使用 PHP header 方法进行重定向,这是(主要是)服务器端的一部分在页面加载后立即结束其所有功能的语言:我的意思是,您拥有的代码会在发出警报或消息之前将用户重定向到您的页面之外。

我建议你做的是 PHP:

    $alert = "this is an alert and gets set whenever something happens";
    //instead of an alert you could also create the paragraph with a button which triggers the redirect.
    echo
    "
        <script>
           window.onload = function(){alert('$alert');}

//this will fire the alert and stop any other thing from happening before the alert is closed

           window.location.href = "https://target_page.com";

//this redirects the user to the wanted page, NB: do use href as other methods may directly redirect without waiting for the alert to display 

        </script>
    ";

让我知道这是否是您要找的:)

我使用了不同的方法。制作了一个 PHP 页面,显示它成功并在 5 秒后重定向它

<html>

<head>
<meta http-equiv="refresh" content="5;URL=http://address.com">
</head>

<body>
    <div id="messagesent">
        <p>Message has been sent successfully<p>
        <p> This page will be redirect after 5 seconds. Please wait ...<p>
      </div>
</body>



</html>