I have an event handler for a form submittal that needs to do some work. That work includes making an ajax call to perform some very specific validations. Because of the asynchronous nature, my intent was to preventDefault at the top of the event handler and, if everything went well, submit the form “manually” by triggering the submit() method.
Of course, that drops me into a loop. If I submit and all goes well, then the submit event handler is called when I resubmit. Is there any way to bypass the handler when I trigger the submit manually?
I should add that my geek karma is on empty today so I may be making this much harder than it has to be. If there’s a dead simple solution for what I’m trying to do, I’d love to hear it.
I should add that I’ve put a working solution in place by simply making the jQuery $.ajax call synchronous, but I can’t help feeling like there’s a more effective way of getting this done that I’m just not seeing today.
Thanks.
Don’t place a submit button on the form, place a button bound as a “validation” mechanism that (when correct) eventually submits.As far as backwards-compatibility, add a submit button, then use jQuery to replace the button with one of your custom-bound buttons (so in the event they don’t support javascript they can still proceed). Afterall, the server should have input validation(s) anyways for these situations/hacking of the form.
Having re-thought it, move your validation logic’s trigger around. Bind to the click event of the submit button. This allows you to intervene just before the
submit()is called. This event should also always return false, as you want to wait for the AJAX response to truly validate weather the form should submit or not.From there, await the AJAX response back, and call submit when all is well.
In regards to backwards-compatibility, you should still have this validation logic server-side in the event that: