php - success message displaying before submit -


i have contact form requires validation. problem success message displaying before hit submit. should display success message once form has passed validation , submitted.

<?php $error = ""; $successmessage = ""; $fname = $email = $message = "";  if ($_server["request_method"] == "post") {   if (empty($_post["name"])) {     $error .= "first name required.<br>";   } else {     $fname = test_input($_post["name"]);     // check if name contains letters , whitespace     if (!preg_match("/^[a-za-z ]*$/",$fname)) {       $error .= "only letters , white space allowed.<br>";      }   }    if (empty($_post["email"])) {     $error .= "email required.<br>";   } else {     $email = test_input($_post["email"]);     // check if e-mail address well-formed     if (!filter_var($email, filter_validate_email)) {       $error .= "invalid email format.<br>";      }   }     if (empty($_post["content"])) {       $error .= "message required.<br>";   } else {     $message = test_input($_post["content"]);   }  }   if ($error != "") {              $error = '<div class="formerror" role="alert"><p><strong>there error(s) in form:</strong><br></p>' . $error . '</div>';  } else {       $successmessage = '<div class="alert alert-success" role="alert">your message sent, we\'ll asap!</div>';               }  function test_input($data) {   $data = trim($data);   $data = stripslashes($data);   $data = htmlspecialchars($data);   return $data; }   ?> 

the form looks this:

<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> 

look @ conditional you're creating success message. set $error variable "". now, you're saying if "" create success message. so, no matter whether request post or not, success message created. move conditional inside block checks whether it's post request.


Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -