开发者

JavaScript two-dimensional Array to PHP

开发者 https://www.devze.com 2022-12-29 15:38 出处:网络
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.

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 ".s开发者_运维技巧ize" 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]</li>";
}

So it works, but it seems very dirty...


Use the auto-array feature in PHP:

var data = {};
$("#add-info .field").each(function(i) {
  data['field['+i+'][name]'] = $(this).find('.name').val();
  data['field['+i+'][type]'] = $(this).find('.type').val();
  data['field['+i+'][size]'] = $(this).find('.size').val()]);
});
$.post("target.php", data);

then on the server side

var_dump($_POST['field']);
// array(
//   0 => array(
//     'name' => ...
//     'type' => ...
//     'size' => ...
//   ),
//   1 => ...

Edit: slightly more elegant version of the loop:

$("#add-info .field").each(function(i) {
  for (attr in {name: 1, type: 1, size: 1}) {
    data['field['+i+']['+attr+']'] = $(this).find('.'+attr).val();
  }
});


Put those input fields in a form-element. Use JSON like

var formData = $('form').serializeArray();
formData     = window.JSON.stringifiy(formData);

$.post('address', {addedfields: formData}, function(){});

something similar to that should do it in jQuery. on the backend convert the JSON into an object and loop through.


Try consider using JSON to interact data between PHP and JavaScript.

JSON is built into Javascript and there is an awesome library for PHP. Check them out.

0

精彩评论

暂无评论...
验证码 换一张
取 消