简体   繁体   中英

Why serialize does not include submit button name?

Why serialize (Jquery) does not include submit button name?

In PHP I normally do this:

if (isset($_POST['submit_signup'])) {
    print_r($_POST);
    //Then check firstname, password, etc POSTS
}

That don't work, what is the solution to this?

Not sure if this is the most elegant solution, but you can use a hidden input box to contain a value (preferably something that changes, like a sort of hash) and check for that. Like:

<input type="hidden" name="signup_submitted" value="random_hash" />

And in your code you can do:

if(isset($_POST['signup_submitted']))
{
    // Do your work;
}

Warning: A hash is not a security thing here, only a way to do the same thing you're used to.

Small Update: I noticed you also asked 'why' JQuery does not include the submit button in the serialize() output. This is default behaviour as specified in the HTML draft(s). As long as no submit button is pressed, it should not be included in the submitted (or serialized) data. The JQuery creators decided to honour that and not include it in the serialized string.

The "value" attribute of the <input> tag of type "submit" is meant to determine a label - the label of the submit button. It is not meant to be sent.

The alternative solution you ask for could be an <input> tag of type "hidden" that holds a value specific to the form it lives in.

Here's an example:

<form method="post">
    <input type="hidden" value="my_form" />
    <!-- Everything else goes here unchanged. -->
</form>

Then in PHP you can use something like the following:

if(isset($_POST["my_form"]))
{
    // Deal with the sent data.
}

It seems to be more elegant workaround to handle the click first and then the submit and combine the array using .serializeArray(); and .push . It works even with forms with more submit buttons:

<script type="text/javascript">
$(document).ready(function() {

    var submitname;
    $("#submit_signup").click(function(event) { 
        submitname='submit_signup'; 
    });


    $('#myform').submit(function( event ){
        var postarray = $('#myform').serializeArray();
        postarray.push({name: submitname, value: 1});

        $.post('script/myscript.php',postarray, function(data){
                /* do what you need with data variable */
            })
    event.preventDefault(); // avoid to execute the actual submit of the form.
    })
})
</script>

In this case, your submit field should have id attribute "submit_signup".

<input type="submit" id="submit_signup" name="submit_signup" value="Submit your form" />

You can check if it is post request in php code:

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM