What happens when you submit a form in javascript?

Summary: in this tutorial, you will learn about JavaScript form API: accessing the form, getting values of the elements, validating form data, and submitting the form.

Form basics

To create a form in HTML, you use the

element:

<form action="/signup" method="post" id="signup"> form>

Code language: HTML, XML (xml)

The element has two important attributes: action and method.

  • The action attribute specifies a URL that will process the form submission. In this example, the action is the /signup URL.
  • The method attribute specifies the HTTP method to submit the form with. Usually, the method is either post or get.

Generally, you use the get method when you want to retrieve data from the server and the post method when you want to change data on the server.

JavaScript uses the HTMLFormElement object to represent a form. The HTMLFormElement has the following properties that correspond to the HTML attributes:

  • action – is the URL that processes the form data. It is equivalent to the action attribute of the element.
  • method – is the HTTP method which is equivalent to the method attribute of the element.

The HTMLFormElement element also provides the following useful methods:

  • submit() – submit the form.
  • reset() – reset the form.

Referencing forms

To reference the element, you can use DOM selecting methods such as getElementById():

const form = document.getElementById('subscribe');

Code language: JavaScript (javascript)

An HTML document can have multiple forms. The document.forms property returns a collection of forms (HTMLFormControlsCollection) on the document:

document.forms

Code language: JavaScript (javascript)

To reference a form, you use an index. For example, the following statement returns the first form of the HTML document:

document.forms[0]

Code language: CSS (css)

Submitting a form

Typically, a form has a submit button. When you click it, the browser sends the form data to the server. To create a submit button, you use or

What happens when a form submits?

Most HTML forms have a submit button at the bottom of the form. Once all of the fields in the form have been filled in, the user clicks on the submit button to record the form data. The standard behaviour is to gather all of the data that were entered into the form and send it to another program to be processed.

How do we submit the form in JavaScript?

In the body tag, created an HTML form and specify the id, method, and action of the form. In the form, specify an anchor tag with an event onclick. Create a function for JavaScript that will get executed when the link is clicked. When we click on the link, the function submitForm() will get executed.

How get response after form submit?

Bookmark this question. Show activity on this post..
Open up the Programmers toolbox..
Go to the console and right anywhere inside it..
In the menu that appears, click "Enable XMXHTTPRequest Logging".