Cesare Cesare - 3 months ago 11
PHP Question

Passing javascript array via POST to PHP does not working

I need to pass a javascript array, via POST, to a PHP file.

I've tried to semplify my original business trying to explain my troubles ...

This is my first PHP file, in which I declare a javascript array and I set each element to 1 value (not a great business I know, but it doesn't matter, it's only to explain ....)

<?php

echo '<form action="testPhp-2.php" method="POST" target="testPhp-2">';

echo '<script type="text/javascript">';

echo 'var arr_selections = [];';
echo 'for(i=0; i < 10; i++)';
echo ' {';
echo ' arr_selections[i] = 1';
echo ' }';

echo 'arr_selections_json = JSON.stringify(arr_selections);';
echo 'alert (arr_selections[2]);';

echo 'document.write("<br/>");';
echo ' ';

// echo 'document.write("<input type="hidden" />");';
echo 'document.write("<input type=\"hidden\" name=\"arr_selections_json\" value=\"arr_selections_json\" />");';
echo ' ';

echo '</script>';

echo ' <input type="submit" value="Controlla">';
echo ' </form>';


?>


.... and here you are the code of testPhp-2 file ...

<?php

if(isset($_POST['arr_selections_json']))
{
echo "OK, array exist !! ";
echo '</br>';
echo '</br>';
$arr_selections = json_decode($_POST['arr_selections_json'], true);
echo $arr_selections[0];
}
else {
echo "NO; array does not exist !! ";
echo '</br>';
echo '</br>';
}

?>


Now, if you try to execute the code you'll see the OK, array exist !! message but no array value is printed about the echo $arr_selections[0]; line of code in testPhp-2.php file.

Any suggestion will be appreciated! Thank you in advance!

Cesare

Answer

Problem is that you're setting the value of the input to the litteral string "arr_selections_json" instead of to the contents of that variable.

Change

echo 'document.write("... value=\"arr_selections_json\" />");';

To

echo 'document.write("... value=\""+arr_selections_json+"\" />");';