I'm having trouble understanding what the form action is used for. It seems like I can handle form data with a Javascript function by setting the onsubmit value to that function. I'm seeing a lot of different examples online that are confusing me even more.
Can someone walk me through what this will do and maybe give me an example of what the form action could do that "onsubmit" can't or shouldn't?
<form onsubmit="someFunction()" action="???"> ... </form>
A user will enter information into the form, then they hit a button to "submit" that information. someFunction() will do stuff with that information... then, the form action is responsible for what? I've seen some examples that look like it just specifies a URL to a page telling the user something like "Thanks for submitting".
I'm sorry if this is confusing. I'm not sure how to ask what I'm confused about. I'm looking for a really simple answer that you might give to a child about what that line of code means for the user and also for the information that was entered into the form.
CodePudding user response:
The difference here is subtle but important:
onsubmit
is an event attribute, meaning whatever JS is in it will be called on thesubmit
event.action
tells the browser where to send the contents of the form when it is submitted in either a GET or POST request (POST by default, unless specified otherwise by themethod
attribute), then reloads the page with the result of the request it sent.
The action
attribute is less customizable because it won't run any of your custom JavaScript, all it will do is send the data to your backend. On the other hand, onsubmit
runs your custom JavaScript, which can do whatever you want (including sending data to your backend). If all you need to do is run some client-side JavaScript when the form submits, use onsubmit
. If all you need to do send data to the server when a form submits, use action
.
Generally, you don't want to use both at the same time because if action
sends data to your backend, then your page will reload. In fact, even if you don't specify an action
attribute, then the page will still reload because it is the default behavior. When using the onsubmit
attribute to run JavaScript when a form is submitted, you'll need to override this default behavior with event.preventDefault()
, hence why most onsubmit
handlers look like this:
function onsubmitHandler(event) {
event.preventDefault()
// ... rest of the code ...
}
CodePudding user response:
onsubmit()
function needed to handle the form submit in JavaScript. When we add the URL
in action attribute, we can't handle the form data in JavaScript. In this case, we can't validate the form data, so the empty data is sent to the server. This will increase server load and it's really bad.