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(";");
Son olarak, PHP formu için bu şekilde gitmek;
document.location.href = "create.php?addedfields=" + addedFields;
PHP kodu ile ilgili olarak, ben explode()
işlevini kullanarak bir PHP dizi oluşturun:
$addedFields = explode(";", $_GET['addedfields']);
ve sonra ben dizide her öğe için tekrar kullanabilirsiniz:
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]</li>";
}
Yani çalışıyor, ama çok kirli görünüyor ...