3

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.

2
  • that sounds odd...you're right it should be showing up. i wonder if it's a browser issue. As a quick fix, I would simply just add an <input type="hidden" name="nameitwhatyouwant" value="already_submitted" /> in the form and then look for that instead. Commented Mar 8, 2013 at 19:16
  • @rnirnber That's what I used to do, but it's so untidy... Commented Mar 8, 2013 at 19:16

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

OK I guess I'll have to use the click() method then. Thanks for your explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.