36

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.

9 Answers 9

45

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.

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

2 Comments

Ah. That makes a lot of sense. I hadn't considered the concept of programatically submitting with multiple submit buttons (I don't use multiple very often). Thanks you ;)
annoying. I am using $form.on('submit', function(){}); which is triggered when the form is submitted (the button is clicked), but even that seems to override allowing the button click through. I tried using onsubmit because onclick was keeping the form from being submitted when i just want to make a change to the page in order to disable buttons from being clicked, but that seems to... disable the buttons... before submitting instead of after... thanks for your explanation!
11

Using a version of jQuery 1.0 or greater:

$('input[type="submit"]').click();

I actually was working through the same problem when I stumbled upon this post. click() without any arguments fires a click event on whatever elements you select: http://api.jquery.com/click/

1 Comment

Just to add my two cents, I was kinda forced to go this way, but discovered that if the <input> button you triggered is currently NOT visible, the value still won't go through.
7

Why not use the following instead?

<input type="hidden" name="submitDocUpdate" value="Save" />

1 Comment

@Tim Cooper - What if there are multiple buttons in the form ?
3

Understanding the behavior is good, but here's an answer with some code that solved my problem in jquery and php, that others could adapt. In reality this is stripped out of a more complex system that shows a bootstrap modal confirm when clicking the delete button.

TL;DR Have an input dressed up like a button. Upon click change it to a hidden input.

html

<input
    id="delete" 
    name="delete" 
    type="button" 
    class="btn btn-danger"
    data-confirm="Are you sure you want to delete?"
    value="Delete"></input>

jquery

$('#delete').click(function(ev) {
        button.attr('type', 'hidden');
        $('#form1').submit();
    return false;
});

php

if(isset($_POST["delete"])){
    $result = $foo->Delete();    
}

Comments

2

The submit button value is submitted when the user clicks the button. Calling form.submit() is not clicking the button. You may have multiple submit buttons, and the form.submit() function has no way of knowing which one you want to send to the server.

Comments

1

Here is another solution, with swal confirmation. I use data-* attribute to control form should be send after button click:

<button type="submit" id="someActionBtn" name="formAction" data-confirmed="false" value="formActionValue">Some label</button>

$("#someActionBtn").on('click', function(e){
    if($("#someActionBtn").data("confirmed") == false){
        e.preventDefault();
        swal({
            title: "Some title",
            html: "Wanna do this?",
            type: "info",
            showCancelButton: true            
        }).then(function (isConfirm) {
            if (isConfirm.value) {
                $("#someActionBtn").data("confirmed", true);
                $("#someActionBtn").click();            
            }
        });     
    }
});

Comments

1

i know this question is old but i think i have something to add... i went through the same problem and i think i found a simple, light and fast solution that i want to share with you

<form onsubmit='realSubmit(this);return false;'>
  <input name='newName'/>
  <button value='newFile'/>
  <button value='newDir'/>
</form>

<script>
  function getResponse(msg){
    alert(msg);
  }

  function realSubmit(myForm){
    var data = new FormData(myForm);
    data.append('fsCmd', document.activeElement.value);
    var xhr = new XMLHttpRequest();
    xhr.onload=function(){getResponse(this.responseText);};
    xhr.open('POST', 'create.php');
    // maybe send() detects urlencoded strings and setRequestHeader() could be omitted
    xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    xhr.send(new URLSearchParams(data));
    // will send some post like "newName=myFile&fsCmd=newFile"
  }
</script>

summarizing...

  • the functions in onsubmit form event are triggered before the actual form submission, so if your function submits the form early, then next you must return false to avoid the form be submitted again when back
  • in a form, you can have many <input> or <button> of type="submit" with different name/value pairs (even same name)... which is used to submit the form (i.e. clicked) is which will be included in submission
  • as forms submitted throught AJAX are actually sent after a function and not after clicking a submit button directly, they are not included in the form because i think if you have many buttons the form doesn't know which to include, and including a not pressed button doesn't make sense... so for ajax you have to include clicked submit button another way
  • with post method, send() can take a body as urlencoded string, key/value array, FormData or other "BodyInit" instance object, you can copy the actual form data with new FormData(myForm)
  • FormData objects are manipulable, i used this to include the "submit" button used to send the form (i.e. the last focused element)
  • send() encodes FormData objects as "multipart/form-data" (chunked), there was nothing i could do to convert to urlencode format... the only way i found without write a function to iterate formdata and fill a string, is to convert again to URLSearchParams with new URLSearchParams(myFormData), they are also "BodyInit" objects but return encoded as "application/x-www-form-urlencoded"

references:

Comments

0

Although the acepted answer is technicaly right. There is a way to carry the value you'd like to assign. In fact when the from is submited to the server the value of the submit button is associated to the name you gave the submit button. That's how Marcin trick is working and there is multiple way you can achive that depending what you use. Ex. in jQuery you could pass

data: { 
    submitDocUpdate = "MyValue" 
}

in MVC I would use:

@using (Html.BeginForm("ExternalLogin", "Account", new { submitDocUpdate = "MyValue" }))

This is actually how I complied with steam requirement of using thier own image as login link using oAuth:

@using (Html.BeginForm("ExternalLogin", "Account", new { provider = "Steam" }, FormMethod.Post, new { id = "steamLogin" }))
{
     <a id="loginLink" class="steam-login-button" href="javascript:document.getElementById('steamLogin').submit()"><img alt="Sign in through Steam" src="https://steamcommunity-a.akamaihd.net/public/images/signinthroughsteam/sits_01.png"/></a>
}

Comments

0

Here is an idea that works fine in all browsers without any external library.

HTML Code

<form id="form1" method="post" >
    ...........Form elements...............
    <input type='button' value='Save' onclick="manualSubmission('form1', 'name_of_button', 'value_of_button')" />
</form>

Java Script

Put this code just before closing of body tag

<script type="text/javascript">
    function manualSubmission(f1, n1, v1){
    var form_f = document.getElementById(f1);
    var fld_n = document.createElement("input");
    fld_n.setAttribute("type", "hidden");
    fld_n.setAttribute("name", n1);
    fld_n.setAttribute("value", v1);
    form_f.appendChild(fld_n);
    form_f.submit();
}
</script>

PHP Code

<?php if(isset($_POST['name_of_button'])){

       // Do what you want to do.
}
?>

Note: Please do not name the button "submit" as it may cause browser incompatibility.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.