Javascript Submit does not include Submit Button Value

Viewed 24492

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.

8 Answers

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();            
            }
        });     
    }
});

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.

Related