user1318194
user1318194

Reputation:

JavaScript form submission doesn't send value of input type=submit

I'm using jQuery to, in some cases, automatically submit a form. Here's my code:

$("form [data-autosubmit]").closest("form").submit();

It works, however it doesn't send the name and value of the input type=submit button.

To elaborate, the following code:

<form method="POST">
<input type="text" name="input" value="text they entered">
<input type="submit" name="submit" value="Submit">
</form>

would send the following POSTdata when submitted by the user:

input: text they entered
submit: Submit

However when the form is submitted by JavaScript, only this POSTdata is sent:

input: text they entered

My PHP scripts rely on the presence of a "submit" value in the POSTdata.

I was thinking I could do:

$("form [data-autosubmit]").closest("form").find("input[type=submit]").click();

But it seems to defy logic, when there is a submit event on the form intended for this purpose.

Upvotes: 3

Views: 4531

Answers (1)

Ben D
Ben D

Reputation: 14479

HTML forms were built to support multiple submit inputs (so the same form could have an "Insert" and "Edit" button, for instance). Therefore the form relies on the click to actually register the chosen field in the _POST submission. Basically, HTML allows a form that looks like this:

<form [...]>
  <input type="submit" name="Insert" value="Insert">
  <input type="submit" name="Update" value="Update">
</form>

to be handled like this on the server-side:

if(!empty($_REQUEST['Update'])){
  //Run update logic here..
}
elseif(!empty($_REQUEST['Insert'])){
  //Run insert logic here...
}

If the Javascript submit() function registered both buttons in the POST array it would break applications using this valid markup/logic, so they default to omitting submit inputs.

So your Javascript workaround (triggering a click on the submit button rather than just submit()ing the form) is the correct approach.

Upvotes: 3

Related Questions