How can I use $_POST to handle dynamic form fields?

Handling dynamic form fields with $_POST involves creating forms with fields that can change based on user input:

<form method="post" action="process.php">
    <div id="dynamic-fields">
        <input type="text" name="fields[0]" placeholder="Field 1">
        <input type="text" name="fields[1]" placeholder="Field 2">
    </div>
    <button type="button" onclick="addField()">Add Field</button>
    <input type="submit" value="Submit">
</form>
<script>
function addField() {
    var container = document.getElementById("dynamic-fields");
    var index = container.children.length;
    var input = document.createElement("input");
    input.type = "text";
    input.name = "fields[" + index + "]";
    input.placeholder = "Field " + (index + 1);
    container.appendChild(input);
}
</script>

In process.php, access the dynamic fields:

<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    foreach ($_POST["fields"] as $field) {
        echo htmlspecialchars($field) . "<br>";
    }
}
?>

This allows users to add fields dynamically, and PHP handles them as part of the $_POST data.

03 Aug 2024   |    7

asked by ~ Megha

Top related questions

How do `echo` and `print` differ in PHP?

18 Aug 2024

   |    28

How Do `isset()` and `empty()` Differ in PHP?

18 Aug 2024

   |    20

How do foreach and for loops differ in PHP?

18 Aug 2024

   |    13

Difference Between Procedural and OOPs in PHP

18 Aug 2024

   |    14

Related queries

Latest questions