提交前显示成功消息

时间:2016-05-28 18:33:35

标签: php

我有一个需要验证的联系表格。问题是成功消息在我甚至点击提交之前显示。显然,一旦表单实际通过验证并提交,它应该只显示成功消息。

<?php
$error = ""; $successMessage = "";
$fname = $email = $message = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["name"])) {
    $error .= "First name is required.<br>";
  } else {
    $fname = test_input($_POST["name"]);
    // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$fname)) {
      $error .= "Only letters and white space allowed.<br>"; 
    }
  }

  if (empty($_POST["email"])) {
    $error .= "Email is required.<br>";
  } else {
    $email = test_input($_POST["email"]);
    // check if e-mail address is well-formed
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $error .= "Invalid email format.<br>"; 
    }
  }


  if (empty($_POST["content"])) {
      $error .= "Message is required.<br>";
  } else {
    $message = test_input($_POST["content"]);
  }

}

 if ($error != "") {

            $error = '<div class="formerror" role="alert"><p><strong>There were error(s) in your form:</strong><br></p>' . $error . '</div>';
 } else {

     $successMessage = '<div class="alert alert-success" role="alert">Your message was sent, we\'ll get back to you ASAP!</div>';


            }

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}


?>

表格如下:

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
  <div class="cform">
    <input type="text" class="contactfield cformbottom" id="name" placeholder="Your full name" name="name" value="<?php echo $fname;?>">

    <input type="email" class="contactfield cformbottom" id="email" name="email" placeholder="Your email" value="<?php echo $email;?>">


    <textarea class="contactfield" id="content" name="content" rows="3" placeholder="Your Message" value="<?php echo $message;?>"></textarea>
          </div>
  <input type="submit" class="newsbut" value="Submit">
</form><br>
         <div id="error"><? echo $error.$successMessage; ?></div>

2 个答案:

答案 0 :(得分:0)

查看您创建成功消息的条件。您已将$ error变量设置为&#34;&#34;。现在,你说的是,如果它是&#34;&#34;然后创建成功消息。因此,无论请求是否为POST,都将创建成功消息。在块中移动该条件,检查它是否是POST请求。

答案 1 :(得分:0)

您的所有验证都应符合以下条件:

if ($_SERVER["REQUEST_METHOD"] == "POST") {

然后,在HTML中,您将检查变量是否存在。例如,

<?php echo isset($successMessage) ? $error . $successMessage : "" ?>
相关问题