In the second scenario you’re getting the only second title, because you need to have unique field names for each field, or one will override the other(s) in $_POST
.
One way to resolve this is to have a single hidden field called perhaps max_id
in which you store the highest id number that you’ve used on the form – so it starts at 1, and is incremented by jquery every time you load another set of form fields.
Then, your php reads that field, and does a basic for loop, starting at 1 up to the max_id
that was submitted and reading the form data from $_POST
. It would look something like this:
$max = $_POST['max_id'];
for ($i=1; $i <= $max; $i++) {
$field_key = 'testfield_' . $i;
// process the form data here...
// you can add suffix to $field_key if you're working with more than just a title field
// i.e. $some_field = $_POST[$field_key . '_some_field']
// which would correspond to $_POST['testfield_1_some_field'], $_POST['testfield_2_some_field'], etc
}
Second scenario
As mentioned in the comments, you need to allow for non-sequential form field IDs. In this case I’d use a different approach. Set up a hidden field and use it store the form field ID (just the numbers is fine), and update this appropriately via jQuery when new sets of fields are added/removed. For example, you may end up with something like this when the form is submitted and processed by PHP: <input type="hidden" name="field_ids" value="1,2,3,5,7" />
Then, your PHP needs to take this hidden field’s value and loop through the fields appropriately:
$field_ids = explode(',', $_POST['field_ids']);
foreach ($field_ids as $id) {
$field_key = 'testfield_' . $i;
// use the fieldkey to access values in $_POST as need be.
}