But in most cases, it’s convenient to have a JavaScript function that handles the submission of the form and has access to the data that the user entered into the form.
What I thought was :
Dealing with form data is not that complicated, so why do I need a function to do it?!
How could I resist to answer with such a nice intro
If you use the action attribute of the <form> the browser will load the specified page. In single page application this is often not desired. We want to stay on the same page and send the entered data in the background to an API. This way we can also handle the response of the API in the same function.
Here is a small excerpt from such a function I use in my code. There is more stuff around those lines, but I think it’s enough to get you an idea. This is from a Vue App.
Using e.preventDefault() is actually a necessary part when using JS to send forms. It stops the page from reloading the current page and giving it the form data. In my example it happens a bit before the code snippet I’ve shown. The question is: “When we prevent the default action, who will send the data and where?” The answer: “Our JS function sends it to an API on our server.”
Having a two-way-binding between state and input fields let us have an object that’s always ready to be sent over JS whenever the submit button is pressed. It also automatically gives us default values.
As an example let’s look at this very forum here:
When I’m hitting reply after writing these lines, my text will be sent to the API and then added below your post. All without reloading the whole code that’s around us.
Additionally, if I later edit my post the edit dialog has my previously written text in its state and thanks to the two-way-binding the text field is automatically populated and ready for me to make changes.
Conclusion
A fundamental property of a modern single page applications is the possibility to change only bits of the page without forcing a reload of the whole app.