【发布时间】:2018-04-25 23:48:04
【问题描述】:
我有一个联系表,我在其中使用 PHP 来完成服务器端的工作。
我遇到的问题是单击提交按钮时表单正在提交,但没有显示表单、错误消息或成功消息。
当我重新加载页面时,会出现表单和相应的消息。
我看不出任何明确的理由来说明为什么会如此有帮助!
<?php
// $error and $success variable set to blank
$error = "";
$successMessage = "";
// check to see if any $_POST variables have been entered
if ($_POST) {
// if $_POST variable ["email"] has no value
if (!$_POST["email"]) {
// $error variable to add comment advising that data is missing
$error .= "An email address is required!!!!!!!!<br>";
}
if (!$_POST["subject"]) {
$error .= "The subject field is required!!!!<br>";
}
if (!$_POST["content"]) {
$error .= "The content field is required!!!!!<br>";
}
// IF $error variable is no longer empty
if ($error != "") {
// $error variable to genereate html + $error
$error = '<div><p><strong>Whoops! There were error(s) in the form:</strong></p>' . $error . '</div>';
} else {
$emailTo = "email@example.com";
$subject = $_POST["subject"];
$content = $_POST["content"];
$headers = "From: ".$_POST["email"];
// IF all email variables have had values assigned then $successMessage to display html sucess message
if (mail($emailTo, $subject, $content, $headers)) {
$successMessage = '<div>Thank you for your enquiry, we will get back to you shortly!</div>';
// ELSE email variable(s) are missing a value - $error variable to display html error message
} else {
$error = '<div>Unfortuantely your enquiry could not be sent, please try again later</div>';
}
}
}
?>
<html>
<div id="contactOuter">
<div id="contactInner">
<a href="javascript:void(0);"><span id="close">×</span></a>
<h1>Get in touch</h1>
<div><? echo $error.$successMessage;?></div>
<form method="post">
<label for="email">Email address:</label><br>
<input name="email" type="email" placeholder="Enter email" id="email">
<label for="subject">Subject:</label>
<input name="subject" type="text" id="subject">
<label for="content">What would you like to ask us?</label><br>
<textarea name="content" rows="7" id="content"></textarea>
<button type="submit" id="submit">Submit</button>
</form>
</div>
</div>
</html>
【问题讨论】:
-
您在
<html>标记之前输出错误消息。查看页面源,它们会在那里,但浏览器不知道如何处理它们,因为它们出现在<html>标记之前 -
您似乎也没有
<body>标签。如果您遵循基本规则,HTML 效果最佳 -
您没有为表单元素指定 ACTION 的任何特殊原因?
-
@RiggsFolly,错误在
echoed 在打开<html>标记之后。我同意<body>的评论。而且,我们应该使用<?php而不是简写<?。我在切换服务器时遇到了问题,我无法控制的新服务器没有处理任何以<?开头的 php,它必须是<?php。我建议看看你是否进入if ($_POST) {块。回声里面和外面的东西。最好使用if (isset($_POST["submit"])) {并将name="submit"放在您的按钮上。