How to make a JSON with an object array

Asked

Viewed 785 times

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 discilpin, ch and stroke. That is, the array that is generated dynamically is something like:

aulas[{"disciplina":"1","curso":"1","ch":"1"},{"disciplina":"2","curso":"2","ch":"2"}]

I used serialize() to generate the JSON of the form, but how do I pass this array in that same JSON so that I can access the data, in php, in the same way as access with the result of serialize().

I tried using stringify, but it doesn’t 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
    }
});

1 answer

0


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

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"] . ", ";
}
  • But how do I get this data in php this way? If I pass the form I can get it with $_POST["fieldDoForm"]. This way it generates only the reference of the form and classes. How I would have to do to get only certain field within the form I passed?

  • I made changes to the answer. See if it helps you.

  • That msmo bro. Helped me peaceful. Thanks :D

Browser other questions tagged

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