2

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!

2 Answers 2

4

use JSON.stringify(array) to encode your array in JavaScript, and then use $arr=json_decode($_POST['jsondata']); in PHP

Sign up to request clarification or add additional context in comments.

Comments

2

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);

1 Comment

may be send them as ajax ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.