HTML5 validation before ajax submit

If you bind to the submit event instead of click it will only fire if it passes the HTML5 validation.

It is best practice to cache your jQuery selectors in variables if you use it multiple times so you don’t have to navigate the DOM each time you access an element. jQuery also provides a .serialize() function that will handle the form data parsing for you.

var $contactForm = $('#contactForm');

$contactForm.on('submit', function(ev){
    ev.preventDefault();

    $.ajax({
        url: "scripts/mail.php",
        type:   'POST',
        data: $contactForm.serialize(),
        success: function(msg){
            disablePopupContact();
            $("#popupMessageSent").css("visibility", "visible");
        },
        error: function() {
            alert("Bad submit");
        }
    });
});

Leave a Comment