How to submit data from a JS array to PHP?

Asked

Viewed 40 times

2

I have a form that has a table that will be generated as the user adds elements to it through the "Add" button. (A customer may have multiple addresses)

As several data will be generated, I will need an array. The only way I know how to do this is by using javascript.

How do I get this javascript data and "play" it on my form Ubmit button? Is there any way I can do this using PHP only?

  • Hello, welcome to the Stackoverflow PT. Enjoy doing the Tour to better understand how the site works. If you think it improves your question, put the code where you need help.

  • Your javascript generates the form according to the user’s click on the add button. Take the fields in PHP normally by the POST. What’s the problem ?

  • For example, if in each user’s "Add", generate a Row for the table, how do I capture each generated data?

  • @user124006 Your "add" does not generate inputs ?

1 answer

1

There are several ways to do this, it would be more interesting if you make the current code available.

Anyway look at the code below. Maybe I can give a light on what to do. In case it doesn’t help let me know I can think of something to help you.

<?php 

print_r($_POST);

?>
<div>

    <form method="post">

        <div>
            <label> Campo 1 </label>
            <input type="text" name='campo[]'>
        </div>

        <div>
            <label> Campo 2 </label>
            <input type="text" name='campo[]'>
        </div>

        <div>
            <label> Campo 3 </label>
            <input type="text" name='campo[]'>
        </div>

        <button> Enviar </button>

    </form>

</div>

The result for the above van is:

Array
(
    [campo] => Array
        (
            [0] => 11
            [1] => 22
            [2] => 33
        )

)

Note that by adding the '[]' at the end attribute 'name' of the input PHP will understand that it is an array. When duplicating address fields you will have as a result for example a CEP field being an array in PHP:

Array
    (
        [cep] => Array
            (
                [0] => 74063-470
                [1] => 75266-392
            )

    )

Browser other questions tagged

You are not signed in. Login or sign up in order to post.