Search code examples
javascriptphpajaxformsserver-side-validation

Processing Dynamic Form


I've a JS dynamic form, where i can add or remove fields:

Field 1
Field 2
Field 3
Field 4

Now if I remove Field 2 and add a new field:

Field 1
Field 3
Field 4
Field 5

I'm sending this through Ajax POST inside a form element. My problem is server side PHP processing. How can I know how many fields I have inside $_POST array and what are their ids? I'm generating unique id using "field" + counterIndex, but following the example how can I be able to understand that I have a total of 4 fields and that number 2 is missing? By the way, inside the form I have static fields too.


Solution

  • This can be done through PHP as $_POST is itself an array thus it can be looped.

    Say, you have fields :

    <input name="dyn[id1]"/>

    <input name="dyn[id2]"/>

    In the backend PHP file,

    Loop through the $_POST as following:

    <?php
    if (isset($_POST['SUBMIT_BTN'])) {
      if (! empty($_POST['dyn'])) {
        foreach ($_POST['dyn'] as $dyn_id => $dyn_val) {
         // "$dyn_id" is your ID you needed.
        }
      }
    }
    ?>