Reputation: 1907
this works:
$('#contestform').on('submit', function(e) {
$.post( '/', $(this).serialize(), function(response){
console.log(response);
},'json' );
e.preventDefault();
});
and this works
jQuery("#contestform").validate();
But I cant figure out how to get them to work together. I want the stuff from the top code to happen only if the submit is clicked and the form is valid. I've tried the stuff from http://docs.jquery.com/Plugins/Validation/validate#toptions but I guess i dont get it. I had it sorta working at one point, but you had to click the submit twice.
One thing is, if I can help it, I want to keep the post() stuff in a separate function, as the two parts will be coming from different parts of the php.
edit 1 tried this, not working (under the form) (by not working, i mean that it is submitting normally, not ajax)
function postForm(e) {
jQuery.post( '/', $(this).serialize(), function(response){
console.log(response);
},'json' );
e.preventDefault();
}
jQuery("#contestform").validate({submitHandler: postForm});
edit2 Well, I got it working with the jQuery.Form plugin http://www.malsup.com/jquery/form/#ajaxSubmit Still, I'd like to know what I was doing wrong in my code above.
function showResponse(responseText, statusText, xhr, $form){
console.log(responseText);
}
var soptions = {
success: showResponse ,
dataType: 'json'
};
jQuery("#contestform").validate({
submitHandler: function(form) {
jQuery(form).ajaxSubmit(soptions);
return false; // always return false to prevent standard browser submit and page navigation
}
});
Upvotes: 2
Views: 2201
Reputation: 6086
The argument to the submitHandler function is not a jQuery event it is the form DOM object. So
to get your edit1 working do this
<script>
$(function () {
$("form").validate({
submitHandler: function (form) {
$.post('/your_url/',
$(form).serialize(), function (response) {
console.log(response);
}, 'json');
}
});
});
</script>
or keeping the the postForm function separate
<script>
$(function () {
function postForm(form) {
$.post('/your_url/',
$(form).serialize(),
function (response) { console.log(response); },
'json');
}
jQuery("form").validate({
submitHandler : postForm
});
});
</script>
Upvotes: 4
Reputation: 191779
function postForm (e) {
$.post(...);
}
jQuery("#contestform").validate({submitHandler: postForm});
Upvotes: 1