phpjquerydata-oriented-design

How to deal with many input fields with the same name, and post to PHP?


Let's say that I have an HTML structure that looks like this. Each left-context-field and right-context-field are related and in the backend it should be possible to link left to its right colleague.

<table>
  <tbody>
    <tr>
      <td>
        <input type="text" class="left-context-field" value="First left value">
      </td>
      <td>
        <input type="text" class="right-context-field" value="First right value">
      </td>
    </tr>
    <tr>
      <td>
        <input type="text" class="left-context-field" value="Second left value">
      </td>
      <td>
        <input type="text" class="right-context-field" value="Second right value">
      </td>
    </tr>
    <tr>
      <td>
        <input type="text" class="left-context-field" value="Third left value">
      </td>
      <td>
        <input type="text" class="right-context-field" value="Third right value">
      </td>
    </tr>
    <tr>
      <td>
        <input type="text" class="left-context-field" value="Fourth left value">
      </td>
      <td>
        <input type="text" class="right-context-field" value="Fourth right value">
      </td>
    </tr>
  </tbody>
</table>

and a user can add as many additional rows as they please. How would I go about posting the values to a PHP file?

Should I wrap all rows in one single huge form, and then call .serializeArray()? Or one form per row?

From a data-oriented approach, what's the best way to deal with this? I'll be sending the data to the back-end, but I want to make the data ass easily accessible for the the backend developer as possible.


Solution

  • I've Edited meda's Answer, but he is not approving that Edit, So I'm posting it here again.

    In HTML forms the way you send arrays is using brackets.

    For example

    name="values[]"
    

    like this.

    <form name = 'vals_form' action = 'php_page.php' method = 'post'>
      <table>
        ... <!-- Your all code -->
        <tr>
          <td>
            <input type="text" class="left-context-field" value="First left value" name="values[]">
          </td>
          <td>
            <input type="text" class="right-context-field" value="First right value" name="values[]">
          </td>
        </tr>
        ...
        <input type = 'submit' value = 'Post Values' />  
      </table>
    </form> <!--and close the form tag-->
    

    In PHP you get the array back

    $values = $_POST['values'];