Send a multidimensional associative arrangement through the use of forms

3

From a form like this:

<form action="action.php" method="POST">
  Foo: <input type="text" name="foo"><br>
  <input type="submit" value="Submit">
</form>

We know that to classically access the information received by the method POST of php is:

$_POST['foo']

That internally it would be something like this:

/*arreglo obtenido por el método POST*/ [
    'foo' => 'bar'
]

Now, what should I modify in the html tags to receive something like this?

[
    'name' => 'example of name',
    'activities' => [
        '0' => [
            'activity' => 'eat'
            'time' => '15:45:12'
            'reason' => 'some explanations'
        ]

        '1' => [
            'activity' => 'sleep'
            'time' => '21:07:12'
            'reason' => 'some explanations'
        ]
        //Se repite N número de veces
    ]
    'rpe' => 'example of rpe',
    'occupation' =>
]

Bearing in mind that the form (being dynamic) I generate it with JavaScript .

NOTE : I want to know what I have to modify in the html tags and how to access the information, ignoring the generation of my form; Any example that has the essence of what I want to achieve, is fine.

Greetings.

    
asked by Arturo G. 17.06.2016 в 17:21
source

3 answers

1

You really do not need JavaScript or process / convert the fields to JSON before submitting the form. In PHP you can use bracket notation that will generate an associative array when the form is processed on the server side.

Just as if you have a field with brackets, an array is automatically generated in PHP when the form is sent, you can define the indexes of that array and the server does the work for you. You just have to make sure that the indexes in the brackets are correct in your HTML and then PHP will take care of the rest.

For example, with the following form:

<form method="post" action="wow.php">

    <input type="text" name="name" />

    <input type="text" name="activities[0][activity]" />
    <input type="text" name="activities[0][time]" />
    <input type="text" name="activities[0][reason]" />

    <input type="text" name="activities[1][activity]" />
    <input type="text" name="activities[1][time]" />
    <input type="text" name="activities[1][reason]" />

    <input type="text" name="rpe">
    <input type="text" name="occupation">

    <button>Submit</button>

<form>

when I do a print_r($_POST) what I get is the associative array:

Array
(
    [name] => Alvaro
    [activities] => Array
        (
            [0] => Array
                (
                    [activity] => Jugar
                    [time] => 1
                    [reason] => Game time!
                )

            [1] => Array
                (
                    [activity] => Estudiar
                    [time] => 2
                    [reason] => Estudiar es bueno
                )

        )

    [rpe] => 12
    [occupation] => Programador
)

which is what you are looking for.

    
answered by 17.06.2016 / 21:00
source
2

And if instead of sending the data of the form that way you collect the values and send them by means of a JSON? If possible, it would be a good way. Both in JS and PHP you have functions to work with it.

In PHP you have json_encode () / json_decode () , in JS you have JSON.stringify () .

Link to SO answer in English about the subject, using array in the forms and collecting values in PHP.

    
answered by 17.06.2016 в 17:33
0

How can you use the DATASET to save more information about your input, here is an example of how to add data to the DATASET of the input. The example is developed with JQUERY, I hope it serves you.

$('#go').click(function() { //Aquí pues un simple click del div que hace funcion de boton, puedes colocar lo que tu ocupes.
  
  //Lo siguiente solo es pleno ejemplo, deberas adecuarlo a tus necesidades.
  
  /*Yo voy a consumir un JSON mediante una página libre*/
        var root = 'http://jsonplaceholder.typicode.com'; //URL de la página 
        $.ajax({
          url: root + '/posts/1', //url con metodos y variables.
          method: 'GET' //uso de GET como Método de Consumo
        }).then(function(data) { //Cuando termine de consultar.
          var a = $("#datos"); //Buscamos el input con id datos
          var b = JSON.stringify(data); // los datos que vienen del consumo los convertimos
          
          //aqui viene el punto clave de la solución
          a.attr("data-a",b); //Vamos a insertar los datos que vienen del consumo en los DATASET del input, entonces creamos el data-a y le agregamos los datos de la variable b.
          a.attr("data-b",b); //como pleno ejemplo hago lo mismo pero ahora con el data-b, tu puedes agregar tantos DATASET como gustes
     console.log("Datos del DATASET a: "+ a.attr('data-a'), "datos del DATASET b: "+a.attr('data-b'));
          
          //OJO: Tu puedes nombrara como gustes a los DATASET, pero siempre con la norma de: data-tunombre, data-otronombre, data-masnombre....
        }
               );
});
#go:hover{
cursor:pointer;
  background:yellow;
  color:red;
}
#go{
width:80px;
background: blue;
  color: white;
  margin: 10px;
  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input id="datos">
  <div id="go">click aqui</div>
</form>
    
answered by 17.06.2016 в 19:07