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

Sparky
  • 98,165
  • 25
  • 199
  • 285
air
  • 6,136
  • 26
  • 93
  • 125
  • 2
    possible duplicate of [HTML5 validation before ajax submit](http://stackoverflow.com/questions/15713491/html5-validation-before-ajax-submit) – omma2289 Sep 02 '13 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. – Will M Sep 02 '13 at 19:42
  • Did you try onsubmit my answer https://stackoverflow.com/questions/18579738/jquery-form-validation-with-ajax-submit-in-codeigniter/54494529#54494529 – Googlian Feb 02 '19 at 15:33

1 Answers1

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>
Googlian
  • 6,077
  • 3
  • 38
  • 44