1

Suppose I have a form with id 'edit-resource' that will appear later in a modal dialog.

I attach a listener to the document like so, such that it will capture the event no matter how many times the modal form is posted back and replaced.

$(document).on('submit', '#edit-resource', function(e) {
    //breakpoint
    //ajax request with new FormData
    return false; //cancel submit
});

When I submit the form, the event handler runs as expected, but by the time the breakpoint is hit... the post has already hit the server (which also has a breakpoint in place). Submit events are supposed to be cancelable (i.e. by returning false), but you can't cancel such an event if it's already hit the server by the first line of the handler. What is causing this issue?

Triynko
  • 18,766
  • 21
  • 107
  • 173

1 Answers1

0

Use .preventDefault

$(document).on('submit', '#edit-resource', function(e) {
    e.preventDefault(); // Will stop your form from submission
    //breakpoint
    //ajax request with new FormData
    return false; //cancel submit
});
void
  • 36,090
  • 8
  • 62
  • 107
  • 1
    Nope. If I break on e.preventDefault... the submission has already hit the server. I have a bad feeling this is a horrific design flaw in JavaScript's event model. In Flash/AS3, it's perfect. The EventDispatcher.dispatchEvent method is called to run handlers, and it returns true or false, indicating whether preventDefault was called on the event. Therefore, no action can take place until after all event handlers have completed and they've all had a chance to call preventDefault. – Triynko Nov 18 '15 at 20:06
  • Something is very wrong with JavaScript's event model (or the debugging system, or starting async operations) if they're allowing form submission through before the handlers return. The return false statement is supposed to cause jQuery to call preventDefault and stopPropagation. They'd be ineffective if the form has already posted data by the time they're called. What 'this' targets in the event is also highly inconsistent in jQuery, depending on whether the event is filtered or not like this, whereas in AS3 the event is a strongly typed object and always has target and currentTarget. – Triynko Nov 18 '15 at 20:12
  • These are supposed to be based on the same ECMAScript spec, and yet nearly a decade after AS3... JavaScript still has it wrong. – Triynko Nov 18 '15 at 20:17
  • This could be a bug introduced 4 years ago in jQuery, notice the fix at the bottom: "Lazy-attach to the genuine submit event for delegation." By the time the delegated event handler has run, the 'real' event has already finished. http://bugs.jquery.com/ticket/7061 Absolutely terrible. This renders the entire system of returning false or calling preventDefault inoperable for delegated event handlers when dealing with submit events. – Triynko Nov 18 '15 at 20:43