Sunday, March 23, 2014

Button click handlers, AJAX, and premature submission

http://encosia.com/button-click-handlers-ajax-premature-submission

Excerpts:

Clicking the button did run our JavaScript code, which we can verify by seeing that the request began. However, it also triggered a form submission since that’s the browser’s default behavior when buttons inside forms are clicked.
 ... 

Putting a leash on the browser’s default behavior

There are a couple ways to tame the browser’s form submission mechanism and make the button work asynchronously, as expected.
  • return false – In almost all cases, an event handler function returning false causes the browser to cancel any subsequent behaviors that the event would normally have triggered (like submitting a form). Using return false works, but you need to be careful about where you place it since the return statement can abort your code early and it can have unintended side-effects.
  • preventDefault() – The browser sends an event parameters to handlers, which details information about the action that triggered the handler. That event object also exposes a method that prevents the browser’s default reaction to that event:preventDefault(). For click handlers on submit buttons inside forms, that includes preventing the form submission.
Since return false does have the issue of sometimes breaking other code and plugins when it stops propagation, I use preventDefault() by… default.


No comments:

Post a Comment

Followers

Blog Archive