# Submitting forms in JavaScript

You already know how to work with JavaScript form elements processing them in the browser. Forms, however, can also be sent to a server to be processed by the backend of the site, written in PHP or NodeJS.

This is necessary in order to add and modify site data stored on a server.

Let's see how it's done. Suppose we have several inputs and a button:

`<input> <input> <input type="submit">`

Let's wrap our elements in the `form` tag. In this case, we will get a form that, when the button is clicked, will be sent to a server:

`<form> <input> <input> <input type="submit"> </form>`

In order for the form data to be received on the server, it is necessary to give each input its own name:

`<form> <input name="test1"> <input name="test2"> <input type="submit"> </form>`

In this case, the form data will be sent to a server in the form of key-value pairs, where the keys will be names of the form elements, and the values will be entered data.

In order to submit a form, there is no need for a server. You can copy the given form code to any file, run it in the browser and click on the submit button - the form will submit and the browser page will reload.

If there is no server, however, the form data will not go anywhere. Therefore, let's check an operation of the form together with the server. You aren't familiar with server-side languages yet, so let's practice submitting a form using our HTTP training server.

Let's place our form in some file so that it is available at `http://localhost:3001/form.html`:

`<form> <input name="test1"> <input name="test2"> <input type="submit"> </form>`

Let's add the `action` attribute to our form, indicating the address of our form submission:

`<form action="/handler/"> <input name="test1"> <input name="test2"> <input type="submit"> </form>`

Now in `server.js` file we will write the form submission address handler:

`export default { '/handler/': function() { return 'form data received'; } }`

The submitted form data will get into the parameter of our handler:

`export default { '/handler/': function(data) { console.log(data); // outputs to the server console return 'form data received'; } }`

Create a form and a file to handle it. Submit the form and check that the data actually came to a server.

← →
↑
en ru