Send a Javascript array to PHP
Few days ago, I’ve encountered this situation: the user clicks on some <li>s, a Javascript function creates an array based on those clicks, and this array has to go to the server, in order to be entered in the database, for safe keeping and further use :)). Everything was supposed to be done without AJAX calls.
The solution
The solution I’ve came up with is pretty simple. Before the form is submitted, I’ve used some javascript to create a lot of hidden inputs, give them the right names and values and add them to the form, using appendChild.
So, just before the submit, my form will look like:
<form action="foo.php" method="post">
<!-- original form tags here-->
<input type="hidden" name="jsArray[1]" value="firstValue" />
<input type="hidden" name="jsArray[2]" value="secondValue" />
<input type="hidden" name="jsArray[3]" value="thirdValue" />
</form>
And in the foo.php file:
<?php
foreach( $_POST['jsArray'] as $key => $value )
{
echo 'jsArray[' . $key . ']=' . $value . '<br />';
}
?>
Or anything else, according to the application’s logic.
Convert javascript array to PHP array
This is the function that does the conversion. Pretty self explanatory, I don’t think anyone will encounter any problems in understanding it. But if you do, just post a comment below.
/**
* appends a javascript array to a form
*
* @param array array - the array
* @param string name - name of the array (set to jsArray in the example above)
* @param mixed form - the form
*/
convertJsArrayToPhpArray = function( array, name, form ) {
if ( typeof( form ) == 'string' ) {
form = document.getElementById( form );
}
var hidden = null;
for( index in array ) {
hidden = document.createElement( 'input' );
hidden.setAttribute( 'type', 'hidden' );
hidden.setAttribute( 'name', name + '[' + index +']' );
hidden.setAttribute( 'value', array[index];
form.appendChild( hidden );
}
}
You can see a live example of this script, here.


?
w00t?
nice + simple = great!!!
thank you
She has become the new voice of the crazy republicans. ,