Error passing JS array values to simple PHP

Asked

Viewed 71 times

1

My code is this down here:

<html>
<body>



<form method="post" action="recebe.php" >
<input type="hidden" id="send_string_array" name="send_string_array" value="" />
<input type="submit" value="Enviar" />
</form> 
</body>
<head>
<script>

//variáveis
var array_produtos = Array([1,2,3,4,5,6]);

var i, array_produtos, string_array;


//varre o array só pra mostrar que tá tudo ok
for (i in array_produtos)
alert(array_produtos[i]);




document.getElementById("send_string_array").value =     array_produtos.join("|");
</script>
</heady>
</html>

The code PHP that should work and show the array is this:

<?php

//transforma a string de itens separados em array
$array_produtos = explode("|", $_POST['send_string_array']);
//mostra o conteúdo do array 
echo $_POST['send_string_array'];

?>

The PHP is returning to me this Array ( [0] => );, but should contain the values in the array, no?

What would be my mistake?

  • 1

    Adailton your new edition has just removed the line I commented below about being the problem, with this current code remains the problem?

  • is because Voce responded while I was editing was bad.

1 answer

2

Your mistake is in javascript, but one remark before, you are defining the array_produtos twice what would be unnecessary.

var array_produtos = Array([1,2,3,4,5,6]); /* aqui */
var i, array_produtos; /* e aqui */

Now about your mistake is on that line

array_produtos = array_produtos.split("|");

The array of javascript has no function split and since your logic doesn’t need that line, remove it and your program will probably work.

Thus remaining the javascript:

<script>

    //variáveis

    var array_produtos = Array([1,2,3,4,5,6]);
    var i;

    //varre o array só pra mostrar que tá tudo ok
    for (i in array_produtos)
        alert(array_produtos[i]);

    document.getElementById("array_produtos").value =      array_produtos.join("|");
</script>

The function split that you were trying to use is when the variable is String, that is, you can use in this way:

var virouString = array_produtos.join("|");
var virouArrayNovamente = virouString.split("|");
  • yes but it does not pass to php, and now I have edited in the code of a look this returning me that in the receives.php Array ( [0] => 1,2,3,4,5,6 ) where it should stay like this, [1,2,3,4,5,6]); .

  • 1

    @adailtonmoraes of the one echo $_POST['send_string_array'] in his php to see how he’s sending this information

  • worked perfectly editing the code with the bugs fixed.

  • 1

    @adailtonmoraes Perfect, if possible mark the answer as the solution. Good evening!

Browser other questions tagged

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