Passing an array from a form to PHP via AJAX

Question:

I have this form:

jQuery

(function($) {
  AddTableRow = function() {

    var newRow = $("<tr>");
    var cols = "";

    cols += '<td><input type="text" name="dados[][nome]" id="dados[][nome]" class="form-control" value=""></td>';
    cols += '<td><input type="text" name="dados[][nome]" id="dados[][nome]" class="form-control" value=""></td>';
    cols += '<td><input type="text" name="dados[][nome]" id="dados[][nome]" class="form-control" value=""></td>';
    cols += '<td><input type="text" name="dados[][nome]" id="dados[][nome]" class="form-control" value=""></td>';
    cols += '<td>';
    cols += '<button onclick="RemoveTableRow(this)" type="button"><span class="fa fa-minus"></button></button>';
    cols += '</td>';

    newRow.append(cols);
    $("#convidados-table").append(newRow);

    return false;
  };
})(jQuery);

To understand better, I modified the code… How would I do this adjustment for array?

Answer:

You can do like this, with an accountant in JS

<input type="text" name="dados[][nome]" class="form-control" value="">
<input type="text" name="dados[][faixaetaria]" class="form-control" value="">
<input type="text" name="dados[][telefone]" class="form-control" value="">
<input type="text" name="dados[][email]" class="form-control" value="">

And in jQuery you can do the same in HTML, without ID and with the same form names .

var cont = 1;
$("#adicionar_convidado").click(function() {
   cont++;
   var campos_novos = "\
   <div class='dep_fc' id='dep_fc'> \
      <div class='col-md-12' style='padding: 5px;'> \
         <div class='col-md-3'> \
            <input type='text' name='dados[nome]["+cont+"]' placeholder='Nome' class='form-control'></div> \
            <div class='col-md-2'><input type='text' name='dados[faixaetaria]["+cont+"]' placeholder='Faixa Etária' class='form-control'></div> \
            <div class='col-md-3'><input type='text' name='dados[telefone]["+cont+"]' placeholder='Telefone' class='form-control'></div> \
            <div class='col-md-3'><input type='text' name='dados[email]["+cont+"]' placeholder='E-mail'  class='form-control'></div> \
            <div class='col-md-1'><button class='btn btn-default remove' type='button'><span class='fa fa-minus'></span></button></div> \
         </div> \
      </div> \
   </div>";
   $("#dep").append(campos_novos);
});

In my case it would return:

"dados" => array:4 [
    "nome" => array:2 [
      0 => "A"
      1 => "E"
    ]
    "faixaetaria" => array:2 [
      0 => "B"
      1 => "F"
    ]
    "telefone" => array:2 [
      0 => "C"
      1 => "G"
    ]
    "email" => array:2 [
      0 => "D"
      1 => "H"
    ]
]

Hence PHP would be:

foreach($dados['nome'] as $key => $value){
    $fe       = $dados['faixaetaria'][$key];
    $email    = $dados['email'][$key];
    $telefone = $dados['telefone'][$key];
    $nome     = $value;
}
Scroll to Top