How to pick variables with repeated names in the ajax method

Asked

Viewed 30 times

0

Come on, I have an AJAX method that takes values from a form and saves them in the session. There are several forms with the same fields, they are generated automatically according to a database, so I cannot use "options 1", "options 2", etc. So I am using "options[]" to get an array au submit the form.

By taking input values that are not repeated in the form I have no problem. However, when trying to get the values of these fields named "options[]", I just get the values from the first form.

The form, briefly, is like this:

<?php foreach($produtos as $key => $valueProdutos) { ?>
  <form class="formulario_produto" method="post" action="crud.php">
    <input type="text" name="nome" value="$valueProdutos['nome']">
    <input type="number" name="preco" value="$valueProdutos['preco']>
    <?php foreach($valueProdutos['opcoes'] as $key => $valueOpcoes) { ?>
      <input type="text" name="opcoes[]" value="$valueOpcoes['valor']">
    <?php } ?>
    <input type="submit">
  </form>
<?php } ?>

THE AJAX:

$('body').on('submit', '.formulario_produto', function submitCB(e) {
  e.preventDefault();
  const adicionar = "1";
  const nome = $("[name='nome']", this).val();
  const preco = $("[name='preco']", this).val();
  const observacoes = $("[name='observacoes']", this).val();
 // Aqui está o local em que pego as informações das variáveis
  $("[name='opcoes[]']", this).each( function() {
    opcoes.push(this.value);
  });
  $.ajax({
    url: 'crud.php',
    type: 'POST',
    data: {
      adicionar: adicionar,
      nome: nome,
      preco: preco,
      opcoes: opcoes
    },
    success: function(response) {
      $('#carrinho').html(response);
    },
    error: function(xhr, status, error) {
      alert(xhr.responseText);
    }
  });
});

And in the crud.php file:

if(isset($_POST['adicionar'])){
  $nome = $_POST['nome'];
  $preco = $_POST['preco'];
  $opcoes = $_POST['opcoes'];
  echo $nome." - R$".$preco." - ";
  foreach ($opcoes as $key => $valueOpcoes ) {
    echo $valueOpcoes;
  }
}

The problem is that I always get the values of the first form, and I only want to get from the sent form

  • Take this one out of here $("[name='options[]']", this). It’s pretty disorganized your code by the way. What the purpose of n Forms will be to send everything via ajax?

  • Dude, I’m not sending out all the forms at once, just whatever I command. As for the "this", I put so that only those who were right-handed of the given form were taken. As for the organization of the code, this is not the proper one, it is only a transcription of the problem so that it can be understood. In that case, I still remove "this"?

  • Give a read https://stackoverflow.com/q/34028678/4623423 . The post addresses a similar problem

  • Thanks, looks like you solved

No answers

Browser other questions tagged

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