Doug Cassidy
Doug Cassidy

Reputation: 1907

jQuery Validate: How to post() after form is valid?

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

Answers (2)

politus
politus

Reputation: 6086

The argument to the submitHandler function is not a jQuery event it is the form DOM object. So

  1. your code will throw an error when you call e.preventDefault();
  2. call $(form).serialize(), not $(this).serialize()

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

Explosion Pills
Explosion Pills

Reputation: 191779

function postForm (e) {
    $.post(...);
}
jQuery("#contestform").validate({submitHandler: postForm});

Upvotes: 1

Related Questions