I have an array in Javascript with many possible sizes. Is there any way for me to pass it to a PHP file for computation?
I would like to use something like a form in html
<form id="barfoo" action="foobar.php" method="post">
<input type="hidden" name="foo">
<input type="hidden" name="bar">
<input type="hidden" name="bam">
</form>
Usually, these inputs are strings. Is there any way to have an array as input to pass? Like fooarray=['abc', 'dbe', '3r']
, or fooarray=['1','c','4','5']
. Before it is generated, I don't know the size of it. Is it possible to put it in a form and pass?
Thanks a lot!
use JSON.stringify(array)
to encode your array in JavaScript, and then use $arr=json_decode($_POST['jsondata']);
in PHP
Encode the array into JSON and then insert it into one of the hiddens. This could be done in the forms onsubmit
event.
<form id="barfoo" action="foobar.php" method="post" onsubmit="populate()">
<input type="hidden" id="foo" name="foo">
</form>
<script>
var fooarray=['1','c','4','5'];
function populate()
{
document.getElementById("foo").value = JSON.stringify(fooarray);
}
</script>
PHP has native support for decoding JSON using json_decode()
:
$fooArray = json_decode($_POST['foo']);
print_r($fooArray);