Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQUERY: how to serialize input fields with same name

I have the following form that has lots of similar type of input fields with same name (eg. 10 fields for 'name', 10 fields for 'address'). How many times these input fields will repeated, can not be said in prior and therefore they cannot be given static different names (eg. 'name1', 'name2', 'address1', 'address2').

Problem: while I am posting data using ajax post (serialized), its only posting the first value of fields with same name (received with php).

Required:

  1. How can I get all the input data posted properly?
  2. Whats the best way to name such input fields that contain similar data for the purpose of catching those data with php (form is generated in php)?

Sample code:

    <form name="content">
     <table>
      <tr>
       <td>
        <input name="full_name" type="text" />
       </td>
       <td>
        <input name="address" type="text" />
       </td>
      </tr>
      <tr>
       <td>
        <input name="full_name" type="text" />
       </td>
       <td>
        <input name="address" type="text" />
       </td>
      </tr>
    </table>
   </form>
like image 982
origin Avatar asked Oct 15 '25 17:10

origin


2 Answers

I think in your case you can use $.serializeArray():

var data = $('form[name="content"]').serializeArray();

this will produce something like this:

data = [
     {
       name : "full_name",
       value : "thefieldvalue"
     },
     {
       name : "address",
       value : "theaddressvalue"
     },
     .....
];

See this:

data:$('form[name="content"]').serializeArray()+'&request=insert_invoice' 

not a correct way to send data instead you can try with this below:

data:{
    frmvalues : $('form[name="content"]').serializeArray(), 
    request:insert_invoice
} 
like image 152
Jai Avatar answered Oct 18 '25 10:10

Jai


<input name="full_name[]" type="text" value="foo" />
<input name="full_name[]" type="text" value="bar" />

In PHP it will be:

Array (
    full_name => Array (
         0 => foo
         1 => bar
    )
)
like image 43
barell Avatar answered Oct 18 '25 11:10

barell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!