Code Computerlove logo Front End Tools & Docs

Earlier today I was reading this tweet by @ZoCodes and was interested in the replies.

What I learnt from this is that the current Front End ecosystem is a complicated place even for the simplest of things that shouldn't need to complicated. Here follows my answer to this question.

Do you need JS to submit a form?

The simplest answer to this question is: no. In fact the HTML <form> element predates JavaScript by two years! What you do need to be able to submit a <form> is an action attribute on the form (pointing to an endpoint that can handle the data) and a submit button, usually in the form (hah) <button>Submit</button>.

The important part here is that you do need an endpoint to handle that data. HTML (via the browser) scoops up all of that data in the form and sends it to whatever URL you put in the action attribute of your form. You can (and probably should) also set a method on the <form> that tells the server what type of request is being sent. This is usually GET or <POST>.

The difference between GET and <POST> is that GET will append the form data to the URL set in the action attriubute. POST will not show any data (making for more secure forms) but allows the server to parse the data and get the fields back out.

An example

Fill in the input and submit the following form.

This form uses a GET request and the current URL. If you look in the URL bar you should see that your name appears there. You can now use whatever method you like to retrieve that data and use it. I can use JavaScript to get the details in the URL and then do whatever I want with that data.

Note that there is no JavaScript used to submit the form or do any validation. That is all handled by the browser using attributes on the form and input field.

What can JavaScript be used for?

JavaScript can be used to add a better experience for users interacting with forms. For example, you could:

  • Use ajax to submit the form to prevent a page reload
  • Give real-time, styled feedback on the state of the form (e.g. inline validation beyond the native browser implementation)
  • Dynamically look up values when fields are changed to change the context of the form rather than having two separate forms
  • Change the display and/or functionality of form fields (such as <select>, which is difficult to style)
  • And a lot more besides

But none of those things are required if you just need a form to submit some data from a webpage to a server. HTML (and the browser) can handle that all by themselves.