I'm validating a Zend form with Ajax and have come up with this:
$('#some-dialog-i-have form').live('submit', function(e) {
e.preventDefault();
MyClass.Form.Validate($(this), function() {
// I wish to submit the form from this callback function
$(this).trigger('submit');
});
});
Where MyClass.Form.Validate takes the form and performs an XHR request to check the form is valid.
My issue is that I wish to continue submitting the form if it is valid, but stop everything if not. Triggering the submit from within this handler will obviously cause a recursive issue; what's the best way to go about this?
Form: {
Validate: function(form, onSuccess) {
$.ajax({
type: 'POST',
dataType: 'json',
url: '/ajax/form/validate',
data: form.serialize() + '&f=' + form.data('id')
}).done(function(errorMessages) {
if(errorMessages.count > 0) {
// Snip (display errors)
return false;
}
// Callback
onSuccess();
});
}
}
Probably a simple solution but my head isn't in the right place today.
Thanks.
One thing that comes to mind would be to have a variable that says whether the form is valid as a result of the Ajax check or not.
If the flag is false, then have your Ajax validation run. Once the Ajax validation comes back as valid, set the flag to true and then when the submit handler is triggered, it sees the flag and bypasses the check and goes directly to submitting the form.
Keep in mind the form should still be validated on the server when submitted in case someone disables JS or a bot tries to post directly to the server and skips the validation step.
Hope that helps.
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