Mr. Developer Mr. Developer - 4 months ago 77
Ajax Question

How can i call function in submithandler using jquery validation?

I'm trying to call ajax function once form validate but it does not work for me. Below jquery

on-submit
method working fine for me.

$('#promotionAdd').on('submit',(function(e) {
e.preventDefault();
var formData = new FormData(this);
promotionAdd(formData);
return false;
}));


But I need to call same thing in submithandler which does not work.

$(document).ready(function () {
$('#promotionAdd').validate({ // initialize the plugin
rules: {
mtitle: {
required: true,
minlength: 3,
}
},
messages: {
mtitle: "Please enter Promotion Title",
},
submitHandler: function (form) { // for demo
//alert(this);
e.preventDefault();
var formData = new FormData(this);
promotionAdd(formData);
return false;
}
});
});


Can any one guide me where i'm wrong and how can i fix it. I would like to appreciate. Thanks

Answer

In the submitHandler this refers to the validation plugin, not the form the plugin was called on. Use the form parameter that's passed in to the function instead.

Also note that preventDefault() will cause an error as e is not defined and return false will do nothing. They are not required here in any case as the validation plugin handles the prevention of the form submission for you. Try this:

submitHandler: function (form) {
    var formData = new FormData(form); // use 'form' here
    promotionAdd(formData);
}