HTML5 validation before ajax submit

前端 未结 6 1615
既然无缘
既然无缘 2020-12-01 01:38

This should be simple, yet it\'s driving me crazy. I have an html5 form that I am submitting with ajax. If you enter an invalid value, there is a popup response that tells y

6条回答
  •  心在旅途
    2020-12-01 01:55

    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");
            }
        });
    });
    

提交回复
热议问题