Javascript Submit does not include Submit Button Value

Joshua Cook picture Joshua Cook · Nov 10, 2009 · Viewed 20.5k times · Source

Ok, this is less of a question than it is just for my information (because I can think of about 4 different work arounds that will make it work. But I have a form (nothing too special) but the submit button has a specific value associated with it.

<input type='submit' name='submitDocUpdate' value='Save'/>

And when the form gets submitted I check for that name.

if(isset($_POST['submitDocUpdate'])){ //do stuff

However, there is one time when I'm trying to submit the form via Javascript, rather than the submit button.

document.getElementById("myForm").submit();

Which is working fine, except 1 problem. When I look at the $_POST values that are submitted via the javascript method, it is not including the submitDocUpdate. I get all the other values of the form, but not the submit button value.

Like I said, I can think of a few ways to work around it (using a hidden variable, check isset on another form variable, etc) but I'm just wondering if this is the correct behavior of submit() because it seems less-intuitive to me. Thanks in advance.

Answer

Peter Bailey picture Peter Bailey · Nov 10, 2009

Yes, that is the correct behavior of HTMLFormElement.submit()

The reason your submit button value isn't sent is because HTML forms are designed so that they send the value of the submit button that was clicked (or otherwise activated). This allows for multiple submit buttons per form, such as a scenario where you'd want both "Preview" and a "Save" action.

Since you are programmatically submitting the form, there is no explicit user action on an individual submit button so nothing is sent.