Tuesday, 20 August 2013

Display PHP Form Validation Results on Same Page

Display PHP Form Validation Results on Same Page

I'm sure the initial reaction is going to be something like, "Doesn't this
guy have Google?" Yes, I'll admit this does seem like a pretty basic
concept and I've tried and tried to wrap my head around it, looked up all
manner of posts and articles on the topic, etc., but all to no avail.
Perhaps you can point me in the right direction?
I have a basic contact form (contact.html) that I run with an external PHP
script (contact.php). Here's the HTML form code:
<form id="form1" action="contact.php" method="post">
<div class="form1">
<label>Your Name:</label>
<span><input type="text" name="name" /></span>
</div>
<div class="form1">
<label>Your School:</label>
<span><input type="text" name="school" /></span>
</div>
<div class="form1">
<label>Phone Number:</label>
<span><input type="text" name="phone" /></span>
</div>
<div class="form1">
<label>E-Mail Address:</label>
<span><input type="text" name="email" /></span>
</div>
<div class="form3">
<span><textarea cols="1" rows="1" name="message"></textarea></span>
</div>
<div class="wrapper">
<input class="submit" type="image" src="images/contact_submit.png"
name="submit" alt="Submit" />
</div>
</form>
The PHP script validates that all of the fields were entered and then
processes the form:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//Validate the name:
if (!empty($_POST['name'])) {
$name = $_POST['name'];
} else {
echo "You forgot to enter your name.<br>";
}
//Validate the school:
if (!empty($_POST['school'])) {
$school = $_POST['school'];
} else {
echo "You forgot to enter your school.<br>";
}
//Validate the e-mail:
if (!empty($_POST['email'])) {
$email = $_POST['email'];
} else {
echo "You forgot to enter your e-mail.<br>";
}
//Validate the message:
if (!empty($_POST['message'])) {
$message = $_POST['message'];
} else {
echo "You forgot to enter a message.";
}
if (!empty($_POST['name']) && !empty($_POST['school']) &&
!empty($_POST['email']) && !empty($_POST['message'])) {
$phone = $_POST['phone'];
$body = "$name\n$school\n$phone\n$email\n\n$message";
mail("***", "PAL Website - Message from a Visitor", $body);
header("Location: confirm.html");
}
}
?>
Everything works great and the form is validated and processed as
intended. However, I REALLY want to set it up so that the error messages
are displayed on the same page or at least have the form refreshed with
the error messages included.
I've seen this done in other demonstrations (Larry Ullman's book, for
example), but still can't quite figure out how to make it happen. Can you
please offer advice? What's the simplest way to go about it?
Here's the page URL, if it helps:
http://www.712jefferson.org/pal/contact.html
Thank you!

No comments:

Post a Comment