views:

375

answers:

3

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]</li>";
}

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

+1  A: 

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.

Kind Regards

--Andy

jAndy
`window.JSON` is not cross-browser.
Tgr
true story, so a simple if(typeof(window.JSON) === 'object') should help out. If it's not available, implement a javascript JSON solution instead.
jAndy
+1  A: 

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();
  }
});
Tgr
A: 

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.

Daniel