1

i have a form. first 2 inputs are simply a customer ID and an address ID. Then the rest is a multidimensional form as the usuer can dynamically add more items.

<div class='invoice_object'>
    <input      name='item[1][quantity]'    type='text'  value=''/>
    <textarea   name='item[1][description]'     ></textarea>
    <input      name='item[1][unit_price]'  type='text'  value=''/>
    <input      name='item[1][amount]'      type='text'  value=''/>
</div>

ANother invoice object can be added with jquery and it would be like so:

    <div class='invoice_object'>
    <input      name='item[2][quantity]'    type='text'  value=''/>
    <textarea   name='item[2][description]'     ></textarea>
    <input      name='item[2][unit_price]'  type='text'  value=''/>
    <input      name='item[2][amount]'      type='text'  value=''/>
</div>

If i post it normally with a submit button then the $_POST variable will contain:

$_POST['customer']
$_POST['address']
$_POST['item'] {
                ['1'] {
                       ['quantity']
                       ['description']
                       ['unit_price']
                       ['amount']
                       }
                ['2'] {
                       ['quantity']
                       ['description']
                       ['unit_price']
                       ['amount']
                       }
                }

I've searched for hours and tried all sorts of versions or serialize and serializeArray.JSON decode etc It seems you can only send a string to php from jquery. Using JSON can get it to the php file but $_POST always ends up just having 1 value and its a string of all the data.

i figured there must be a way of doing it... without manually making a function that dissects the string acording to where the square brackets are.

i could do with some advice please. Thanx. But without panually dissecting

jquery

    var x = $('#new_invoice').serialize();

    $.post("script/new_invoice_script.php", {
                    x                       
                    }, function(data) {     
                    console.log (data);
                    });
dragonvsphoenix
  • 120
  • 1
  • 11

2 Answers2

3

You shouldn't put x inside another object. It's already in the format necessary for the data argument to $.post.

var x = $('#new_invoice').serialize();
$.post("script/new_invoice_script.php", x, function(data) {
  console.log(data);
});

When you write { x } it's the ES6 shorthand for { x: x }. That puts the serialized input string into $_POST['x'].

Barmar
  • 596,455
  • 48
  • 393
  • 495
0

The .serialize() method creates a text string in standard URL-encoded notation. It can act on a jQuery object that has selected individual form controls, such as , , and : $( "input, textarea, select" ).serialize();

You need use .serializeArray()