简体   繁体   中英

Submit multiple forms as one

I have two forms on the page. To the user it looks like 1 form, and I actually wish it was one form. But the way I'm trying to reuse code and include things, I can't avoid two forms in the source code... trying to act as one.

I don't want to do ajax submit, I want a normal post submit, my form handler has redirects in it. How can I submit both of these, and get values that make sense on the server side. something like $_POST['form1]['whatever'] $_POST['form2]['thing']

Maybe take all the inputs from form 2, rename all of them with a prefix, and append them to form 1? I can't find a non-messy way of doing this. I don't think I need code, just a plan. Least messy idea wins.

Maybe take all the inputs from form 2, rename all of them with a prefix, and append them to form 1?

That's exactly what you have to do. Wouldn't be much of an answer without a code sample, so here you go.

$("#form2 :input").appendTo("#form1")[0].submit()

now in php you'll have $_POST['thing'] containing an array with two values. Alternatively you can rename all of the inputs from form2:

$("#form2 :input").attr("name",function(name){
    return name + "_form2";
}).appendTo("#form1")[0].submit();

您可以尝试使用jQuery.serializeArray()收集一个表单的值,然后生成hidden输入,其中包含来自变量的名称和值,存储以前称为jQuery.serializeArray() ,并将它们插入到表单的submit事件的第二个表单中。

You should be able to combine both forms fields into one single form in PHP. If your code doesn't allow it, it must be in terrible shape.

If you are using simple scripts, you should be able to cut the forms into parts producing the fields, and the other parts producing the form outlines, either as separate scripts, or simply as separate functions.

ie:

<?php 

    function form_body($params) {
        // here's the code for echoing fields according to $params
    }

    function form($params) {
        // here's the code to build the form properties 
        $f_properties = '....';
        echo '<form '.$f_properties.'>';
        form_body($params);
        echo '</form>';
    }

?>

Then it's just a matter of combining $params from form1 and form2 to get the definitive form.

If you're using OOP, it's probably very easy to derive a new class containing both forms, and have it output their fields.

This are very simplistic advices, but you don't provide any source to help refactoring, so I can only provide vague/generic code examples.

Going the js way to combine forms on the client side will turn into a lot of problems down the line to maintain and evolve the code, and bring a lot of issues (security not the least of them).

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