JavaScript two-dimensional Array to PHP
Posted
by vi
on Stack Overflow
See other posts from Stack Overflow
or by vi
Published on 2010-05-06T13:17:07Z
Indexed on
2010/05/06
13:28 UTC
Read the original article
Hit count: 145
Hi
I have to send a two-dimensional JavaScript Array to a PHP page.
Indeed, I'm working on a form-builder, in which the user can add or remove fields.
These fields are added (or removed) using JavaScript (jQuery). When the user is done and hit a 'publish' button, I have to get all the fields concerned and send them to a PHP page which would build a real form with it.
I found a way to do it but I'm pretty sure it's not very clean :
addedFields = new Array();
$("#add-info .field").each(function() {
addedFields.push(new Array($(this).find('.name').val(), $(this).find('.type').val(), $(this).find('.size').val()));
});
Basically, the ".field
" class objects are <tr>
and the ".name
", ".type
" and ".size
" objects are inputs.
So I get an array of [name, type, size]
, then I convert it into a string using
addedFields = addedFields.join(";");
Finally, I go to the PHP form that way ;
document.location.href = "create.php?addedfields=" + addedFields;
Concerning the PHP code, I create a PHP array using the explode()
function:
$addedFields = explode(";", $_GET['addedfields']);
and then I use it again for each element in the array:
foreach ($addedFields as $field) {
$field = explode(",", $field);
echo "<li>Field with name : '$field[0]', of '$field[1]' type and with a size of $field[2]";
}
© Stack Overflow or respective owner