Why use a form tag when you're submitting via ajax?
Philosophical question:
Say I've got a web app that requires javascript and a modern browser, so progressive enhancement is not an issue. If my form is being built via javascript, and my data updates are all being done via ajax POSTs & PUTs, is there really any reason to wrap my controls in a form tag? If I'm still going to use the tag, say for semantic or structural reasons, is there any reason to have action and method params that I'm going to ignore? It kind of feels like a hold-over from an earlier era to me.
Solution 1:
There is at least one important user-experience feature provided specifically by wrapping inputs inside a form tag:
The enter key will submit the form. In fact, in Mobile Safari, this is how you get the "Go" button to appear on the keyboard.
Without a form wrapping the inputs, there is nothing to submit.
You can of course provide enter-key behavior through a keypress event, but I don't know about if this works for mobile devices. I don't know about you, but I'd rather work with the semantics provided by the browser than have to imitate them with events.
In your case, you would simply provide an onsubmit
event handler for the form, which would do your AJAX submit, then return false
, canceling the actual submit.
You can simply provide action=""
(which means "self"), and method
is not required — it defaults to GET
.
Solution 2:
If you do not need progressive enhancement, you theoretically don't need them.
On the other hand, form
s have some cool grouping and semantic effects. Using them, you can group your form elements logically, and make it easier for your scripts to gather the values of certain elements.
For example if you want to ajax-submit some user input, it is always easier to say: "let's take all elements in this form and submit them" than saying "let's take this input, these two selects and these three textareas and submit them". In my experience, it actually helps the developer if form
tags are present.
Solution 3:
AJAX is great but as JamWaffles (+1 to him) said, using form
tags provides a fallback method.
Personally I use form tags, even for things I submit with AJAX because it is syntactically clear and makes it easy to grab all inputs within a specific form. Yes you could do this with a div
or whatever too but as I said, using a form is syntactically nice.
Incidentally, screen readers treat the content inside a form
differently so there are accessibility issues to be considered whichever way you choose to go. Note that anecdotal evidence suggests that Google considers accessibility in its rankings so if SEO is a concern for you, use a form and do it right.