I'm trying to create a form that is validated front end using Parsley.js and submitted asynchronously. The form is called #contactForm and the submit button is #sendData, the error comes when I hit submit on an empty or invalid form. I expect to see an 'Error' alert from invalid form data but instead it just continues with the Else condition and the data is processed by contactForm.php.
$(document).ready(function() {
// submit data on click and check if valid
$('#sendData').click(function(e) {
//check if valid with parsley
var valid = $('#contactForm').parsley ( 'validate' );
if ( valid === false )
{
e.preventDefault();
}
else
{
$.post("contactForm.php", $("#contactForm").serialize());
}
});
});
Proper solution below.
Here's how your code should look like.
$(function() {
$('#contactForm').submit(function(e) {
e.preventDefault();
if ( $(this).parsley().isValid() ) {
$.post("contactForm.php", $(this).serialize());
}
});
});
=== false
explicitly. (Parsley will return a truthy value when the form is valid, just use that.)$(document).ready(function() { ...
is $(function() { ...
.{
on the one line that started the statement.)EDIT: In older versions of parsely (before 2.x), use
if ( $(this).parsley('validate') ) {
// ...
}
This is what worked for me:
<form id="signupform" data-parsley-validate>
(....)
</form>
<script>
$(function() {
$('#signupform').parsley().subscribe('parsley:form:validate', function (formInstance) {
formInstance.submitEvent.preventDefault(); //stops normal form submit
if (formInstance.isValid() == true) { // check if form valid or not
//code for ajax event here
$.post("createuser.php", $(#signupform).serialize());
}});
});
</script>
Yes, it is copied from parsleyjs.org examples. But it works fine!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With