Send Array JS By ajax to PHP

2

I capture several inputs (the value) dynamically in the following way:

<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>

  <input type="text" name="prueba" class="form-control-file nombrePaisIdioma"><br/><br/>
  <input type="text" name="prueba" class="form-control-file nombrePaisIdioma"><br/><br/>
  <input type="text" name="prueba" class="form-control-file nombrePaisIdioma"><br/><br/>
    <input type="text" name="prueba" class="form-control-file nombrePaisIdioma"><br/><br/>

  <input type="button" onclick="x();" class="btn btn-primary" id="enviardoc" value="Enviar Documentos">

<script type="text/javascript">

  function x(){

    var nombres_paises = {};

    $('.nombrePaisIdioma').each(function() {
        nombres_paises[$(this).attr('id')] = $(this).val();
        console.log(nombres_paises);

    });

        $.ajax({
        type : 'POST',
        data : {'nombres_paises': JSON.stringify(nombres_paises)},//capturo array  
        url : 'pruebacolor2.php',
        success : function(e){

          console.log(e);

        }
        });




}

</script>

So far we are doing well, since I capture them all.

The problem is that in PHP, only 1 comes, the last one:

<?php


    $data = json_decode($_POST['nombres_paises']);
    var_dump($data);

?>

I hope you can help me, because I do not know what the problem is.

Thanks

    
asked by Andres Rodriguez 06.12.2018 в 22:59
source

1 answer

1

Your problem is in this line:

nombres_paises[$(this).attr('id')] = $(this).val();

You are acquiring the id of the inputs, but the inputs have no id. The solution is to add the ids to the inputs or you can simply do:

nombres_paises.push($(this).val());
    
answered by 06.12.2018 / 23:17
source