Hi everyone,
I have a contact form which I’m validating with PHP. How would I add jQuery Ajax to the form so that the page doesn’t reload when the form is submitted and error messages are displayed? Or can I do this without using Ajax at all?
I’ve had a look at the jQuery validation plugin https://github.com/jzaefferer/jquery-validation and I like the way the error messages disappear when the correct values are entered into the form inputs. Is this a good plugin to use?
My main concern is how to combine the PHP validation with the jQuery validation. If I use FILTER_VALIDATE_EMAIL to validate the email address then how do I use this with the jQuery validation?
I’m trying to wrap my head around this whole PHP/JavaScript validation.
Any guidance would be appreciated. Thank you in advance!
This is my simplified form and PHP validation:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors = array();
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
if (!$name) {
$errors['name'] = 'Please enter your name.';
}
$email_address = filter_var($_POST['email_address'], FILTER_VALIDATE_EMAIL);
if (!$email_address) {
$errors['email_address'] = 'Please enter a valid email address.';
}
$comment = filter_var($_POST['comment'], FILTER_SANITIZE_STRING);
if (!$comment) {
$errors['comment'] = 'Please enter a comment.';
}
if ($name && $email_address && $comment) {
$body = "Name: {$name}\
\
";
$body = wordwrap($body, 70);
mail('simon@whatever.com', 'Contact Form Submission', $body, "From: {$email_address}");
echo '<p><em>Thanks for the comment dude!.</em></p>';
$errors = array();
}
}
?>
<form id="myform" name="contact" action="" method="post">
<p>Name:
<span class="warning"><?php if (isset($errors['name'])) echo $errors['name']; ?></span></p>
<input type="text" id="name" name="name" value=
"<?php if (isset($name)) echo $name; ?>" />
<p>Email address:
<span class="warning"><?php if (isset($errors['email_address'])) echo $errors['email_address'];?></span></p>
<input type="text" name="email_address" value=
"<?php if (isset($email_address)) echo $email_address; ?>" />
<p>Add a comment:
<span class="warning"><?php if (isset($errors['comment'])) echo $errors['comment']; ?></span></p>
<textarea id="text_area" rows="11" cols="72" name="comment"></textarea>
<input type="submit" name="send" id="send_button" value="Send">
</form>