简体   繁体   English

表单提交后如何在不同的php文件处理的html表单下显示成功消息

[英]How to show success message below html form after form submit which is being handled by different php file

There is a form in my index.php file. 我的index.php文件中有一个表格。 This form is handling from a different php file named send-mail.php . 此表单是从另一个名为send-mail.php php文件处理的。 I want to show a message inside alert div in index.php file. 我想在index.php文件的alert div中显示一条消息。 Can this be done by php or javascript will be needed too? 可以通过php或javascript完成吗?

index.php: index.php文件:

<section id="contact">
<form action="send-mail.php" id="form" method="post" name="form">
   <input id="name" name="name" placeholder="your name" type="text" required>
   <input id="email" name="email" placeholder="your e-mail" type="email" required>
   <textarea cols="50" id="message" name="message" placeholder="your enquiry" rows="4" required></textarea>
   <input type="submit" name="submit" id="submit" value="Send Message">
</form>
<div class="alert alert-dismissible fade in hide" role=alert>
   <button type=button class=close data-dismiss=alert aria-label=Close><span aria-hidden=true>&times;</span></button>
</div>
</section>

send-mail.php: 发送-mail.php:

<?php
if(isset($_POST['submit'])){
    // Get the submitted form data
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];

    // Recipient email
    $toEmail = 'user@example.com';

    $emailSubject = 'Contact Request Submitted by '.$name;
    $htmlContent = '<h2>Contact Request Submitted</h2>
        <h4>Name</h4><p>'.$name.'</p>
        <h4>Email</h4><p>'.$email.'</p>
        <h4>Message</h4><p>'.$message.'</p>';

    // Set content-type header for sending HTML email
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

    // Additional headers
    $headers .= 'From: '.$name.'<'.$email.'>'. "\r\n";

    // Send email
    if(mail($toEmail,$emailSubject,$htmlContent,$headers)){
        $statusMsg = 'Your contact request has been submitted successfully !';
        $msgClass = 'alert-success';
        header('location: index.php#contact');
    }else{
        $statusMsg = 'Your contact request submission failed, please try again.';
        $msgClass = 'alert-danger';
        header('location: index.php#contact');
    }

}
?>

Change your redirects to: 将您的重定向更改为:

header('location: index.php?result='.$msgClass.'#contact');

Then adding the following to your index.php file: 然后将以下内容添加到您的index.php文件中:

if ($_GET['result']=="alert-success") {
    // display success message here
} elseif ($_GET['result']=="alert-danger") {
    // display error message here
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM