I'm basically trying to
- Get the form validated
- Redirect to a success page (response.php) if validated
My Form's HTML. It's just a feedback form with sticky PHP.
<form method="post" action="">
<fieldset>
<legend>Contact Form</legend>
<label>Name (Required)</label>
<input name="name" type="text" placeholder="Enter your name. (e.g. Arthur)" value="<?php if(isset($_POST['name'])) echo htmlspecialchars($_POST['name']);
?>">
<span class="err"><?php echo $nameErr;?></span>
<label>Email (Required)</label>
<input name="email" type="email" placeholder="Enter a valid e-mail. (e.g. someone@host.com)" value="<?php if(isset($_POST['email'])) echo htmlspecialchars($_POST['email']);
?>">
<span class="err"><?php echo $emailErr;?></span>
<?php
if (isset($_POST['reason']))
{
$reasonVar = $_POST['reason'];
}
?>
<label>Reason</label>
<select name="reason">
<option <?php if($reasonVar=="question") echo 'selected="selected"'; ?> value="question">Question</option>
<option <?php if($reasonVar=="feedback") echo 'selected="selected"'; ?> value="feedback">Feedback</option>
<option <?php if($reasonVar=="suggestions") echo 'selected="selected"'; ?> value="suggestions">Suggestions</option>
<option <?php if($reasonVar=="other") echo 'selected="selected"'; ?> value="other">Other</option>
</select>
<label>Message (Required)</label>
<textarea name="message" placeholder="Enter your message. (e.g. Your website is awesome!)" ><?php if(isset($_POST['message'])) echo htmlspecialchars($_POST['message']);?></textarea>
<span class="err"><?php echo $messageErr;?></span>
<input class="sub" name="submit" type="submit" value="Submit">
</fieldset>
</form>
Here is the PHP for the page. It's just doing basic validations on the form, and attempting to use the header function to redirect the page to response.php after all the validation is successful (hence the long if statement).
<?php
$nameErr = $name = "";
$emailErr = $email ="";
$messageErr = $message ="";
if ($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty(trim($_POST["name"]))){
$nameErr="Missing";
}
else{
$name = $_POST["name"];
}
if(empty(trim($_POST["email"]))){
$emailErr = "Missing";
}
elseif(!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)){
$emailErr = "Invalid";
}
else{
$email=$_POST["email"];
}
if(empty(trim($_POST["message"]))){
$messageErr="Missing";
}
else{
$message = $_POST["message"];
}
if(!empty(trim($_POST["name"]))&&!empty(trim($_POST["email"]))&&filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)&&!empty(trim($_POST["message"]))){
header("Location:response.php");
exit;
}
}
?>
Right now, if the form validates, the form just disappears and I'm stuck on the form page without redirecting to the success page. I'm very new to backend web coding so any help would be greatly appreciated. Thank you so much in advance!