I am using jQuery and Ajax for some areas of a site and I cannot for the life of me work out how to only submit the Ajax if the form is valid. For normal jQuery validation I am using jquery.validate.min.js like this:

$("#po-login-form").validate();

This works fine.
I then have ajax functionality in some areas as such:

$('#po-login-box .login-send').click(function (e) {
    e.preventDefault();
        $.ajax({
            url: 'po-login.php',
            data: $('#po-login-box form.do-login').serialize() + '&action=send',
            type: 'POST',
            success: function(html) {
                if (html == 'success') {
                    $('#po-login-box #po-login').hide("fast");
                    $('#mask , .login-popup').delay(1500).fadeOut(300 , function() {
                        $('#mask').remove();
                    });
                    window.location.href = 'checkout-delivery.php';
                } else {
                    $('#po-login-box .login-error').show("fast");
                }
            }
        });
});

Again it works fine.

Now my problem - I can't work out how to combine the 2 to ensure the form is valid before it submits (at the moment the ajax is firing regardless of what I do. I have tried using an if statement around the ajax and beforeSubmit within the ajax but neither works.

if($("#po-login-form").validate({
    $.ajax({
        // ajax here
    })
}); // This gives me an error in the console

$.ajax({
    beforeSubmit: $("#po-login-form").validate(),
    // All other ajax here
}); //This just submits the form without validating

There must be a way to do this and must be a fairly normal requirement but I can't seem to work it out or find anything online to help.

It's OK, all sorted - I just run the two separately using the normal form validation and then my ajax and that works

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.