0

I am trying to create a contact form with CI and I am having problem with jQuery triggering HTML5 validation, my form is

<form id="contact_form" name="contact_form">
    <INPUT id="name" class="medium user" name="name" type="text" required>
    <input type="submit" name="submit_btn" id="submit_btn" value="Send Message">
</form>

with this html validation is working fine but when I try to submit form with Ajax using bellow code, validation stop working and form submitted without validation

$(document).ready(function($){
    $("#submit_btn").click(function(){

        var response = $.ajax({
            type: "POST",
            url: "send_email.php",
            data: $(contact_form).serialize()
        }).done(function( msg ) {


         $('#commentForm').html('<h5>Thanks</h5>'+msg);


});

        return false;
    });  
});

how to validate form with ajax form submission?

Thanks

3
  • 2
    possible duplicate of HTML5 validation before ajax submit Commented Sep 2, 2013 at 19:37
  • Try handling submission with the submit event rather than a click event. All HTML5 form validation is handled by the browser, so a general click won't trigger validation. Commented Sep 2, 2013 at 19:42
  • Did you try onsubmit my answer stackoverflow.com/questions/18579738/… Commented Feb 2, 2019 at 15:33

1 Answer 1

0

Use submit method instead of click if you want to validate the form and submit ajax.

$(document).ready(function($) {
    $("#contact_form").submit(function() {

        alert('form submitted');
        
        var response = $.ajax({
            type: "POST",
            url: "send_email.php",
            data: $("#contact_form").serialize()
        }).done(function(msg) {
            $('#commentForm').html('<h5>Thanks</h5>' + msg);
        });

        return false;
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form id="contact_form" name="contact_form">
    <INPUT id="name" class="medium user" name="name" type="text" required>
    <input type="submit" name="submit_btn" id="submit_btn" value="Send Message">
</form>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.