Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 208
sprugman Avatar asked Jun 10 '11 16:06

sprugman


People also ask

Why do I need a form tag?

The HTML form tag is required when you want to collect information that visitors provide. For example, you may want to collect specific data from visitors, such as name, email address, and password. The HTML <form> tag is used to create a form.

Does AJAX require a form?

With AJAX, there is really no need to use a form - you can do exactly the same thing without navigating away from the current page (unless you then specifically code it to do so).

What is AJAX form submission?

AJAX form submitting allows you to send data in the background, eliminating the need to reload websites to see the updates. This makes the user experience much smoother.

What is the difference between AJAX and form submit?

A standard form submit sends a new HTTP request (POST or GET) and loads the new page in the browser. In Ajax, the data is sent to the server (POST or GET) in the background, without affecting the page at all, and the response is then received by javascript in the background, again without affecting the page at all.


1 Answers

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.

like image 182
Nicole Avatar answered Oct 04 '22 05:10

Nicole