views:

22

answers:

1

i'm using jQuery validate() plugin to validate a form. it does the validation but how do i perform a set of function if there are no errors?

i've tried this

$(document).ready(function() {
    $('form').validate({
        submitHandler: function(form) {
        $.post('php/contact.php', { 
            name: $('form #name').val(), 
            email: $('form #email').val(), 
            comments: $('form #comments').val() },
            function(data) {
                if(data.success) {
                    alert('thank you');
                }
                else {
                    alert('error');
                }
        }, 'json');
        form.submit();
    }
    });
});

The form validates but i'm not getting data.success as true from php now. any ideas?

+1  A: 

Use the submitHandler option for this:

$("form").validate({
  //rules, etc..
  submitHandler: function(form) {
    //do something, it was valid
  }
});

The opposite handler for this is the invalidHandler which executes when the submitted form was not valid.

Nick Craver
thanks. i tried this but it's still not working.
pixeltocode
@pixeltocode: Which part? You're making an ajax request then submitting the form (probably cancelling that request), what isn't working?
Nick Craver
when i put the $.post within a .click() function, the form submits. when add the validate(), it validates the form and submits it. when i use the submitHandler, nothing happens.
pixeltocode
@pixeltocode - Did you try putting just an alert in? (Also in the `invalidHandler` since your form may be invalid) Currently you're not adding any validation rules...so why are you even using the validation plugin?
Nick Craver
i'll be adding the rules once i get this working :)
pixeltocode
@pixeltocode - You're saying the form is not submitting at all?
Nick Craver
if it submits i data.success will be true and the alert should work, right?
pixeltocode
@pixeltocode - You're firing off an ajax request, then submitting the form which abandons the AJAX call, if you want it to only run when `data.success` is there, you should move `form.submit();` into that if statement, but you're being *very* unclear about what doesn't work...
Nick Craver
@Nick Craver, as you pointed out, the problem was form.submit(). removed it and now the ajax call is made only if the required field are filled. cool...thanks! +1 for you
pixeltocode