Submit Buttons and Ajax

April 10, 2009

We’re writing an Ajax webapp with progressive enhancement. In other words, if JavaScript is disabled, it should work – but if JavaScript is enabled, it should work better. As a general pattern, then, all of the buttons in our app are submit buttons that execute server-side behavior. When the page loads, we attach click event listeners to the buttons, to call the appropriate JavaScript methods.

By default, though, the submit buttons still try to submit the form. But we need to disable that, so that only the Ajax call happens. The first solution I tried was:

document.getElementById("myform").onsubmit=function(){return false;};

This disabled form submission altogether, which worked just fine.

The problem arose when we had a form that had to have some submit buttons work, but not all. It’s a shopping cart page, and we want “Checkout” to still submit the form and go to the checkout page; but we want the “Remove” buttons to execute Ajax calls to remove elements. They’re all in the same form, because, for example, if the user updates a quantity for one product, then removes another product, they expect the quantity change to be saved as well. So one big form.

The best solution I found for this was to actually create a new button-button, and use it to replace the submit button. At first, this seemed a bit clunky. But the problem is that the submit button wants to submit the form, and I was having trouble finding a way to prevent it from submitting. Rather than messing with its internals, it’s cleaner to create a button-button, that doesn’t want to submit.