Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Triggering jquery event from within the same event handler

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();
        });
    }
}
  • I've through about stopPropagation, but this will have no effect on the live handler
  • I am aware the live() handler is deprecated, I have neglected to change it for the moment
  • I've thought about simply posting the form through Ajax, but not sure if I want to do it this way

Probably a simple solution but my head isn't in the right place today.

Thanks.

like image 522
James Avatar asked Jul 22 '26 16:07

James


1 Answers

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.

like image 53
drew010 Avatar answered Jul 25 '26 08:07

drew010



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!