jQuery validator plugin + ajax submitting not working

Your ajax belongs inside the submitHandler callback function of the jQuery Validate plugin.

As per docs,

submitHandler, Callback, Default: default (native) form submit

Callback for handling the actual submit when the form is
valid. Gets the form as the only argument. Replaces the default
submit. The right place to submit a form via Ajax after it
validated
.

Your other problem is that you’re calling .validate() twice. After it’s called the first time, the other instance is ignored and so are all the rules you’re trying to pass into it. The .validate() method gets called ONE time upon DOM ready to initialize the plugin on your form.

Finally, you don’t need to put a submit handler into the submitHandler callback function.

DEMO: http://jsfiddle.net/nTNLD/1/

$(document).ready(function () {

     $("#contactform").validate({
         ignore: ":hidden",
         rules: {
             name: {
                 required: true,
                 minlength: 3
             },
             cognome: {
                 required: true,
                 minlength: 3
             },
             subject: {
                 required: true
             },
             message: {
                 required: true,
                 minlength: 10
             }
         },
         submitHandler: function (form) {
             $.ajax({
                 type: "POST",
                 url: "formfiles/submit.php",
                 data: $(form).serialize(),
                 success: function () {
                     $(form).html("<div id='message'></div>");
                     $('#message').html("<h2>Your request is on the way!</h2>")
                         .append("<p>someone</p>")
                         .hide()
                         .fadeIn(1500, function () {
                         $('#message').append("<img id='checkmark' src="https://stackoverflow.com/questions/15625195/images/ok.png" />");
                     });
                 }
             });
             return false; // required to block normal submit since you used ajax
         }
     });

 });

Leave a Comment