How to make a JSON with an array of objects

0

I have a form that is sent via POST as JSON. But I have an object array called classes [] in JavaScript. The object contains disciple, ch and course. That is, the array that is dynamically generated is something like:

, "ch": "2"}]

I used serialize () to generate the JSON of the form, but how do I pass that array on the same JSON so that I can access the data in php just like access with the result of serialize () / p>

I tried to use stringify, but it does not have a reference like the other form fields.

$.ajax({
    type: "POST",
    data:  $('#form').serialize()+JSON.stringify(aulas),
    url: "includes/post.php",
    success: function(msg){
        //teste
    }
});
    
asked by anonymous 24.01.2018 / 15:10

1 answer

0

You can use jQuery serializeArray() to transform form values into json. The problem is that this serialization usually returns objects similar to { 'name' : 'nome', 'value' : 'João' } and for the server side to treat this information as an object, we use $.each to scroll through form values and create an "associative array", or in case , a json object:

// constrói o 'array associativo', criando um objeto e atribuindo à ele os parâmetros e valores
var formulario = {};
$.each($("#form").serializeArray(), function() {
    formulario[this.name] = this.value;
});

// envia as informações para o servidor
$.ajax({
    type: "POST",
    data: {
        "formulario" : formulario,
        "aulas" : aulas
    },
    url: "includes/post.php",
    success: function(msg){
        //teste
    }
});

For you to recover these two values in php, you will have to use something like:

$formulario = $_POST["formulario"];

// acessando os valores do formulário
echo $formulario["nome_do_campo_do_formulario"];
echo $formulario["outro_do_campo_do_formulario"];

$aulas = $_POST["aulas"];

// acessando os valores do array de aulas
foreach($aulas as $aula) {
    echo $aula["disciplina"] . ", ";
}
    
24.01.2018 / 15:44