Combining JQuery Validation followed by ajax post
Solution 1
.validate()
can be configured by passing in an object with various configuration options. In this case, setting the submitHandler
with a callback to your form submission code should do the job.
I've also cleaned up your example code a bit, in an effort to show you how to write more idiomatic jQuery.
I've used
jQuery.post()
instead ofjQuery.ajax()
sincejQuery.ajax()
is a low-level method which is only used when you want to customize the behaviour of an AJAX request, much like how we're customizing the behaviour of.validate()
.All inputs of the form can be prepared for posting by invoking
.serialize()
. This prepares a URL encoded key-value string likename=John+Doe&email=john%40doe.com
, which can then serve as data for a POST.
$(document).ready(function() {
$('#myForm').validate({
submitHandler: function(form) {
$.post('subscript.php', $('#myForm').serialize());
}
});
});
Solution 2
You ought to be able to use the submitHandler
option, which would essentially be a callback function which is invoked when the form is validated:
$('#submit').click(function () {
$("#subscribe-form").validate({
submitHandler: function(form) {
//do 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.
Solution 3
You can do something like the following before your ajax call to invoke validation:
if (!$('form').valid()) {
return false;
}
Textus
Updated on June 14, 2022Comments
-
Textus about 2 years
I'm sure this is simple but I'm new to JQuery. I am using the JQuery plugin to validate an email address, this works and the code is:
$(document).ready(function () { $("#email").click(function () { $(this).attr({value: ''}); }); $("#subscribe-form").validate(); });
What I then want to do is to post the email address using an ajax post, again this code works fine without the validator:
$(document).ready(function () { $('#submit').click(function () { var email = $('#email').val(); var data = "email=" + email; $.ajax({ type: "POST", url: "subscript.php", data: data, }); }); });
What I don't seem to be able to do is combine them both, so that if the email is valid it will then post. I'd really appreciate help on how to do this.
Thanks very much