jQuery Form Validation before Ajax submit

Tom picture Tom · Jul 13, 2012 · Viewed 250.2k times · Source

JavaScript bit:

$(document).ready(function()
    {
            $('#form').submit(function(e)
            {     

                e.preventDefault();
                var $form = $(this);

                // check if the input is valid
                if(! $form.valid()) return false;
                    $.ajax(
                    {
                    type:'POST',
                    url:'add.php',
                    data:$('#form').serialize(),
                    success:function(response)
                    {
                        $("#answers").html(response);
                    }
                });     

            })
    });

HTML bit:

    <input type="text" name="answer[1]" class="required" />
    <input type="text" name="answer[2]" class="required" />

So this is the code I am trying to use. The idea is to get all my inputs validated before I send my form with Ajax. I've tried numerous versions of this now but every time I end up with submitting even though the form is not entirely filled out. All my inputs are of the "required" class. Can anyone see what I am doing wrong?

Also, I depend on class-based requirements as my input names are generated with php so I can never be sure what name[id] or input types I get.

I show/hide questions as I go through it in "pages".

<input type="button" id="next" onClick="toggleVisibility('form3')" class="next-btn"/>

JS:

function toggleVisibility(newSection) 
        {
            $(".section").not("#" + newSection).hide();
            $("#" + newSection).show();
        } 

Answer

Darin Dimitrov picture Darin Dimitrov · Jul 13, 2012

You could use the submitHandler option. Basically put the $.ajax call inside this handler, i.e. invert it with the validation setup logic.

$('#form').validate({

    ... your validation rules come here,

    submitHandler: function(form) {
        $.ajax({
            url: form.action,
            type: form.method,
            data: $(form).serialize(),
            success: function(response) {
                $('#answers').html(response);
            }            
        });
    }
});

The jQuery.validate plugin will invoke the submit handler if the validation has passed.