Sobes.tech
Junior

How does an HTML form work and what is needed to submit it?

sobes.tech AI

Answer from AI

An HTML form is an interactive element of a web page used to collect user data. It consists of control elements (input fields, submit buttons, checkboxes, radio buttons, etc.) enclosed within a <form> tag.

When the form is submitted, data from all control elements inside the <form> tag are collected and sent to the specified server address.

Key attributes of the <form> tag:

  • action: the URL where the form data will be sent.
  • method: the HTTP method used to send data (GET or POST).
    • GET: Data is appended to the URL as query parameters. Visible in the address bar. Suitable for data requests (e.g., search). Limited length.
    • POST: Data is sent in the body of the HTTP request. Not visible in the address bar. Suitable for sending confidential data or large volumes.

Components necessary for submitting a form:

  1. <form> tag: a wrapper for form elements.
  2. Control elements: input fields (<input>), text areas (<textarea>), dropdown lists (<select>), etc., each with a name attribute (for identifying data upon submission) and a value (the data to be sent).
  3. Submit button: <button type="submit"> or <input type="submit">. Initiates the data submission process.
  4. action and method attributes: define where and how the data will be sent.
  5. Server application: must accept and process the data sent by the form. A Node.js application can use frameworks like Express to parse form data from the request body (req.body for POST) or URL parameters (req.query for GET).

Example of a simple form:

<form action="/submit-data" method="post">
  <label for="name">Name:</label><br>
  <input type="text" id="name" name="name"><br>
  <label for="email">Email:</label><br>
  <input type="email" id="email" name="email"><br><br>
  <button type="submit">Submit</button>
</form>

Example of processing in Node.js (with Express):

const express = require('express');
const app = express();
const port = 3000;

// For parsing req.body (POST requests)
app.use(express.urlencoded({ extended: true }));

app.post('/submit-data', (req, res) => {
  const formData = req.body; // Form data is available in req.body
  console.log('Received form data:', formData);
  res.send('Data received!');
});

app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});
How does an HTML form work and what is needed to… - sobes.tech