我创建了一个联系表单,我希望当用户发送邮件时,会显示“已发送您的邮件”消息而不是联系表单,保留在同一页面上我该如何解决?
这是我的代码
<form method="post" action="" name="contact">
<div class="column">
<input name="name" id="name" placeholder="name" value=""/>
</div>
<div class="column-2">
<input name="email" id="email" placeholder="mail" value="" />
</div>
<div class="column-3">
<textarea id="message" placeholder="Your message" name="message" title="votre message" ></textarea>
</div>
<div class="button">
<span><input class="submit" id="submit" name="submit" type="submit" value="ENVOYER"></span>
</div>
</form>
PHP代码
<?php
if(!empty($_POST['name'])&&!empty($_POST['email'])&&!empty($_POST['message']))// check if everything has been filled out before doing anything else
{
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: test Contact';
$to = 'test@test.com';
$subject = 'Hello';
$body = "From: $name\n E-Mail: $email\n Message:\n $message";
if ($_POST['submit']) {
if ($name != '' && $email != '') {
if (mail ($to, $subject, $body, $from)) {
echo '<p>Your message has been sent!</p>
<span id="success">OK</span>';
} else {
echo '<p>Something went wrong, go back and try again!</p>';
}
}
}
}
?>
答案 0 :(得分:0)
你必须使用AJAX。然后从您的AJAX调用您的PHP代码(您需要将您的PHP放在一个单独的文件夹中)
答案 1 :(得分:0)
你有三种选择。
答案 2 :(得分:0)
如果您想要实现它,那么您必须将成功或失败的页面重定向到另一个页面。我已经更改了您的代码结构,因为您需要首先检查表单是否已提交。
以下是工作示例。
index.php页面
<?php
if (isset($_POST['submit'])) {
if (!empty($_POST['name']) && !empty($_POST['email']) && !empty($_POST['message'])) {// check if everything has been filled out before doing anything else
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: test Contact';
$to = 'test@test.com';
$subject = 'Hello';
$body = "From: $name\n E-Mail: $email\n Message:\n $message";
if ($name != '' && $email != '') {
if (mail($to, $subject, $body, $from)) {
header("Location: result.php?success=1");
} else {
header("Location: result.php?success=0");
}
} else {
echo "Name and Email not found";
}
} else {
echo "Please fill up all fields";
}
}
?>
<form method="post" action="" name="contact">
<div class="column">
<input name="name" id="name" placeholder="name" value=""/>
</div>
<div class="column-2">
<input name="email" id="email" placeholder="mail" value="" />
</div>
<div class="column-3">
<textarea id="message" placeholder="Your message" name="message" title="votre message" ></textarea>
</div>
<div class="button">
<span><input type="submit" class="submit" id="submit" name="submit" value="ENVOYER"></span>
</div>
</form>
result.php page
<?php
if (isset($_GET['success']) && $_GET['success'] == 1) {
echo '<p>Your message has been sent!</p><span id="success">OK</span>';
} else {
echo '<p>Something went wrong, go back and try again!</p>';
}
?>