How to combining bassistance.de jquery validator with jquery ajax
I have a form that I would like to validate client side and then post through ajax. I have the form working using one or the other but am not sure how to combine them. Having visited bassistance ajax pages I am left more confused than before.
Client side:
jQuery(document).ready(function() {
jQuery("#this_form").validate({
});
});
Ajax:
jQuery("#submit").click(function(){
var formData = jQuery("#this_form").serializeArray();
jQuery.ajax({
type: "POST",
url: "process_form.php",
cache: false,
data: formData,
success: onSuccess,
error:开发者_StackOverflow中文版 onError
});
return false;
});
What I would like to know is how I can trigger the ajax on successful validation combining the two methods above. I am asking on the assumption that there is a straight forward way of doing so as all the tuts I find bear little resemblance to the above code.
Have tried this:
jQuery(document).ready(function() {
$('#submit').live('click', function(event){
event.preventDefault();
var form = $('#this_form');
if(form.valid()){
var formData = jQuery("#this_form").serializeArray();
jQuery.ajax({
type: "POST",
url: "process_form.php",
cache: false,
data: formData,
success: onSuccess,
error: onError
});
return false;
};
});
});
But this doesn't validate the required field and just does the ajax. I guess what I am looking for is a way of the validator returning true without submitting the form and then firing off the ajax event but I don't know how to construct this.
Thanks
Try this:
$("#button").click(function(){
if($("#form").valid()){
//Ajax submission
}
});
And in your button you can add a type="button"
to prevent the automatic submission.
Sorted with this:
jQuery(document).ready(function() {
jQuery("#this_form").validate({
debug: true,
rules:{
// add rules here
},
messages: {
//add messages here
}
},
submitHandler: function(form){
jQuery.ajax({
type: "POST",
url: "processform.php",
cache: false,
data: jQuery(form).serialize(),
success: onSuccess,
error: onError,
});
}
});
});
function onSuccess(data, status)
{
data = jQuery.trim(data);
jQuery("#return_message").html(data);
}
function onError(data, status)
{
// handle an error
}
精彩评论