View Full Version : passing javascript array and var to php

02-25-2011, 05:55 PM
I'm submitting data from a form to another page. Using the onsubmit event I'm generating a javascript array and var which I want to access both the array and var using $_POST. The array and var I'm assuming need to be passed as POST parameters. If so, in what format exactly, as they are not values within the submitting document?

03-01-2011, 01:07 PM
You can pass the Array easily with JSON format:
var aray = ["elm1", "elm2", ...];
Then, in php you can use json_decode() function.

About vars, I think you can put them in an JSON object
var vars = {"var1":"val1", "var2":"val2", ...};
Then, in php

$vars = json_decode($_POST['vars']);
foreach($vars as $k => $v) {
$$k = $v;

03-01-2011, 01:18 PM
Another option is to create dynamically hidden textbox elements in the onsubmit function and attach them to the form before the form is submitted. The hidden textboxes can contain the values in the var and the array. Make sure the name of the hidden textboxes for the array values have the same name and have [] appended to the name so they are sent as an array to the php script.

03-01-2011, 02:15 PM
My tabular form has rows

<td><input type'checkbox' name='checkbox' value'x-y-z'></td>
<td><textarea name='text'>Text goes here</textarea></td>
I originally had the textarea disabled to prevent users from editing the text. This however was preventing $_POST from reading the text. So now the textarea is not disabled, the text is now visible to $_POST, but the user can edit the text which I don't want. If there is no way of displaying and posting the text without preventing the user from editing the text, I might have to just display the text like x, y and z, and collect the text from a database instead. Unless there is any other solution?