I have created a form and the problem I am having is that if the user does not enter a required field, then they press submit and it tells them they missed the field out on a new page, therefore they have to click the back button.
I am wondering if it can be done in a way which the user would see that it has not been entered on the actual page, without taking them to a new one.
Below is the php file code:
- Code: Select all
<?php
/* Set e-mail recipient */
$myemail = "random@email";
/* Check all form inputs using check_input function */
$firstname = check_input($_POST['firstname'], "Enter your first name");
$lastname = check_input($_POST['lastname']);
$email = check_input($_POST['email']);
$number = check_input($_POST['number']);
$comments = check_input($_POST['comments'], "Write your comments");
// Where to redirect after form is processed.
$url = 'http://www.....com/thanks.html';
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email))
{
show_error("E-mail address not valid");
}
/* Let's prepare the message for the e-mail */
$message = "Message from the ... website enquiry form.
Your contact form has been submitted by:
First Name: $firstname
Last Name: $lastname
E-mail: $email
Number: $number
Comments:
$comments
Do you agree to the terms and conditions? $terms
End of message
";
/* Send the message using mail() function */
mail($myemail, $subject, $message);
/* Redirect visitor to the thank you page */
echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$url.'">';
exit();
/* Functions we used */
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}
function show_error($myError)
{
?>
<html>
<body>
<b>Please correct the following error:</b><br />
<?php echo $myError; ?>
</body>
</html>
<?php
exit();
}
?>
And here is the HTML code for the form:
- Code: Select all
<form action="enquiry_form.php" method="post">
<p><b>First Name:</b> <input type="text" name="firstname" /><br /><br />
Last Name: <input type="text" name="lastname" /><br /> <br />
<b>E-mail:</b> <input type="text" name="email" /><br /><br />
Number: <input type="text" name="number" /><br /><br />
<p><b>Your comments:</b><br /><br />
<textarea name="comments" rows="10" cols="40"></textarea></p><br /><br />
<p><b>Do you agree to the terms and conditions?</b>
<input type="radio" name="terms" value="Yes" checked="checked" /> Yes
<input type="radio" name="terms" value="No" /> No
<br /><br />
<p><input type="submit" value="Send"></p>
<p> </p>
</form>
The help would be much appreciated. Thanks!


