[英]how do i display a custom message after submitting a form?
我有一个 html 表单,它在提交后使用 phpMailer 发送 email。 一切正常,但我想在发送 email 时在表单上显示一条消息。 使用我的代码,一条消息显示在空白页上。
我的 php 代码:
<?php
$name = $_POST['name'] ?? '';
$email = $_POST['email'] ?? '';
$msg = $_POST['msg'] ?? '';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
$mail->Host='smtp.gmail.com';
$mail->SMTPDebug = 0;
$mail->isSMTP();
$mail->Port=587;
$mail->SMTPAuth=true;
$mail->SMTPSecure='tls';
$mail->Username='email@email.com';
$mail->Password='password';
$mail->setFrom($email, $name); // who send the email
$mail->addAddress('email@email.com'); // who recive the email
$mail->isHTML(true);
$mail->Subject = 'Portfolio response';
$mail->Body = $msg;
$mail->send();
echo 'Your message has been sent!';
} catch (Exception $e){
echo '';
}
?>
您的留言已发送! 显然是显示的消息。
Html 形式代码:
<form action="mail-handler.php" method="POST" id="contact-form">
<span class="contacts-text" id="first-contacts-text">To get in touch with me, please compile this form.</span>
<span class="contacts-text">I will reply as soon as possible. Thank you!</span>
<ul class="form-content">
<li class="form-input">
<label for="name" class="label">Full name</label>
<input class="input" id="name" type="text" name="name" required>
</li>
<li class="form-input">
<label for="email" class="label">E-mail</label>
<input class="input" id="mail" type="text" name="email" required>
</li>
<li class="form-input">
<label for="msg" class="label">Insert text</label>
<textarea class="input" id="comment" type="text" name="msg" cols="30" rows="10" style="resize: none;" required></textarea>
</li>
<li class="form-input" id="last-input">
<input class="input" id="form-button" type="submit" value="submit" name="submit" onclick="sendEmail()">
</li>
</ul>
</form>
谢谢指教!
首先,将index.html
的名称更改为index.php
,这样它就可以被 PHP 解释器解析。
接下来修改您的成功声明正文,即:
try {
$mail->send();
header('Location: index.php?mailsent=1');
die(); // we don't want exactly anything after sending redirect header.
} catch (Exception $e){
echo '';
}
如果$_GET['mailsent']
变量可用,最后在您的表单文件中添加消息。
HTML code of your page...
...
<?php
if (isset($_GET['mailsent']) && intval($_GET['mailsent']) == 1 ){
echo '<div class="messagesbox">Mail was sent</div>';
}
?>
<form action="mail-handler.php" method="POST" id="contact-form">
... your form body skipped here
</form>
如果不想通过 GET 数组传递 arguments,可以尝试使用会话。
此外,您可以创建一个thankyou.html
页面并在提交邮件后将用户重定向到那里
此外,如果将表单提交的整个 PHP 代码移动到index.php
中,则无需进行重定向。
最后,正如您添加的那样 - 虽然它是单页网站,但您还应该考虑使用 AJAX 可能与 jQuery - 这样您就可以在不离开页面的情况下提交表单,在不重新加载的情况下显示消息等。无论如何,这个主题绝对过于宽泛,无法在此答案中进行描述,我只能建议您熟悉jQuery AJAX 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.