Reputation: 3
I have problem with jquery validation and ajax form submit.
Here's validation code:
$(function() {
$("#contact-form").validate({
rules: {
name: {
required: true,
minlength: 2,
maxlength: 32
},
email: {
required: true,
email: true
},
message: {
required: true,
minlength: 20
}
},
messages: {
name: {
required: "Please, enter a name",
minlength: $.format("Keep typing, at least {0} characters required"),
maxlength: $.format("Whoa! Maximum {0} characters allowed")
},
email: {
required: "Please, enter an email",
email: $.format("Please, enter valid email")
},
message: {
required: "Please, enter a message",
minlength: $.format("Keep typing, at least {0} characters required")
}
},
submitHandler:function(form) {
form.submit();
}
});
});
Here's ajax code for submitting the form:
$(document).ready(function(){
$('#contact-form').on('submit',function(e) {
$('#name').val('Your Name');
$('#email').val('Your Email');
$('#message').val('Your Message');
$.ajax({
url:'',
data:$(this).serialize(),
type:'POST',
success:function(data){
console.log(data);
$("#success").show().fadeOut(10000);
},
error:function(data){
$("#error").show().fadeOut(10000);
}
});
e.preventDefault();
});
});
What I try to do is form validation and then submit the form. After submit the form should appear again with initial values.
The problem is that when I remove ajax then validation works fine, but I need ajax code to re-display the form.
How I could make this two pieces of code work together?
Upvotes: 0
Views: 224
Reputation: 20459
Place your ajax call within the submitHandler function:
submitHandler:function(form) {
//form.submit();
$.ajax({
url:'', //you will need a url surely, perhaps $(form).attr('action');
data:$(form).serialize(),
type:'POST',
success:function(data){
console.log(data);
$('#name').val('Your Name');
$('#email').val('Your Email');
$('#message').val('Your Message');
$("#success").show().fadeOut(10000);
},
error:function(data){
$("#error").show().fadeOut(10000);
}
});
}
Upvotes: 1