Reputation: 9289
I would like to create a comment form based on the jquery validation plugin (http://docs.jquery.com/Plugins/Validation). How do I configure the form to submit using AJAX? Right now I cant get the form to submit without going to the next page (process.php). I want it to stay on the form page.
The code is pretty much straight from jquery currently.
<script>
$(document).ready(function () {
$("#commentForm").submit(function () {
if ($("#commentForm").validate()) {
$.ajax({
type: 'POST',
url: 'process.php',
data: $(this).serialize(),
success: function (returnedData) {
$('#commentForm').append(returnedData);
}
});
}
return false;
});
});
</script>
<form class="cmxform" id="commentForm" method="POST" action="process.php">
<label for="cname">Name</label>
<em>*</em><input id="cname" name="name" size="25" class="required" minlength="2" />
<label for="cemail">E-Mail</label>
<em>*</em><input id="cemail" name="email" size="25" class="required email" />
<label for="curl">URL</label>
<em> </em><input id="curl" name="url" size="25" class="url" value="" />
<label for="ccomment">Your comment</label>
<em>*</em><textarea id="ccomment" name="comment" cols="22" class="required"></textarea>
<input class="submit" type="submit" value="Submit"/>
And the php is pretty standard too:
<?php
$to = '[email protected]';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: [email protected]' . "\r\n" .
'Reply-To: [email protected]' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
print "Form submitted successfully: <br>Your name is <b>".$_POST['cname']."</b> and your email is <b>".$_POST['email']."</b><br>";
?>
Thanks for any help.
Upvotes: 2
Views: 3664
Reputation: 10407
$(document).ready(function(){
$("#commentForm").submit(function(){
if($("#commentForm").validate()){
$.ajax({
type: 'POST',
url: 'process.php',
data: $(this).serialize(),
success: function(returnedData){
alert(returnedData);
}
});
}
return false;
});
});
Upvotes: 2