How to access javascript array in php on submit

Suppose you have a Javascript array and want to send it to the server side on page submit then you can use this method.

Suppose we have a Javascript array with 3 elements:

var test = ["test1", "test2", "test3"];

Now create a hidden variable in HTML. This variable will be set to the Javascript array values on submit:

<input id="hidden_js_aid" type="hidden" name="hidden_js_array">

1. Submit button click needs to call Javascript function setArrayToHidden():

<form action="target Server controller" method="post"&gt
<input type="submit" name="button1" value="create my learning plan" onclick="setArrayToHidden();"&gt
</form&gt

2. In setArrayToHidden function we will put the array in the hidden variable:

function setArrayToHidden()
{
document.getElementById('hidden_js_aid').value=test;  
}

Now hidden_js_aid variable will contain the array element values like this:

<input id=”hidden_js_aid” type=”hidden” name=”hidden_js_array” value=”test1,test2,test3”>

3. On the server side retrieve the value like below and explode it to convert back into array:

$data = $_POST['hidden_js_array'];
$test_array=array();
$test_array=explode(',', $data);
echo "<pre>";print_r($test_array);echo "<pre>";

Output:

Array
(
  [0] =>test1
  [1] =>test2
  [2] => test3
)

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *