Multi-step Form Builder JavaScript, PHP

👤 Sharing: AI
```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Multi-Step Form</title>
    <style>
        body {
            font-family: sans-serif;
        }

        .form-step {
            display: none;
        }

        .form-step.active {
            display: block;
        }

        .navigation-buttons {
            margin-top: 20px;
        }

        .navigation-buttons button {
            padding: 10px 20px;
            margin-right: 10px;
            cursor: pointer;
        }

        #response-message {
            margin-top: 20px;
            padding: 10px;
            border: 1px solid #ddd;
            background-color: #f9f9f9;
            display: none;
        }
    </style>
</head>
<body>

    <h1>Multi-Step Form</h1>

    <form id="multi-step-form" action="submit.php" method="POST">

        <!-- Step 1: Personal Information -->
        <div class="form-step active" data-step="1">
            <h2>Personal Information</h2>
            <label for="firstName">First Name:</label>
            <input type="text" id="firstName" name="firstName" required><br><br>

            <label for="lastName">Last Name:</label>
            <input type="text" id="lastName" name="lastName" required><br><br>

            <label for="email">Email:</label>
            <input type="email" id="email" name="email" required><br><br>
        </div>

        <!-- Step 2: Address -->
        <div class="form-step" data-step="2">
            <h2>Address</h2>
            <label for="address1">Address Line 1:</label>
            <input type="text" id="address1" name="address1" required><br><br>

            <label for="address2">Address Line 2:</label>
            <input type="text" id="address2" name="address2"><br><br>

            <label for="city">City:</label>
            <input type="text" id="city" name="city" required><br><br>
        </div>

        <!-- Step 3: Contact Information -->
        <div class="form-step" data-step="3">
            <h2>Contact Information</h2>
            <label for="phone">Phone Number:</label>
            <input type="tel" id="phone" name="phone" required><br><br>

            <label for="additionalNotes">Additional Notes:</label>
            <textarea id="additionalNotes" name="additionalNotes" rows="4" cols="50"></textarea><br><br>
        </div>

        <!-- Navigation Buttons -->
        <div class="navigation-buttons">
            <button type="button" id="prev-button" disabled>Previous</button>
            <button type="button" id="next-button">Next</button>
            <button type="submit" id="submit-button" style="display: none;">Submit</button>
        </div>
    </form>

    <div id="response-message"></div>


    <script>
        const form = document.getElementById('multi-step-form');
        const steps = Array.from(document.querySelectorAll('.form-step'));
        const prevButton = document.getElementById('prev-button');
        const nextButton = document.getElementById('next-button');
        const submitButton = document.getElementById('submit-button');
        const responseMessage = document.getElementById('response-message');
        let currentStep = 1;

        function showStep(stepNumber) {
            steps.forEach(step => step.classList.remove('active'));
            document.querySelector(`.form-step[data-step="${stepNumber}"]`).classList.add('active');
            currentStep = stepNumber;

            if (currentStep === 1) {
                prevButton.disabled = true;
            } else {
                prevButton.disabled = false;
            }

            if (currentStep === steps.length) {
                nextButton.style.display = 'none';
                submitButton.style.display = 'inline-block';
            } else {
                nextButton.style.display = 'inline-block';
                submitButton.style.display = 'none';
            }
        }

        nextButton.addEventListener('click', () => {
            if (currentStep < steps.length) {
                showStep(currentStep + 1);
            }
        });

        prevButton.addEventListener('click', () => {
            if (currentStep > 1) {
                showStep(currentStep - 1);
            }
        });


        form.addEventListener('submit', function(event) {
            event.preventDefault(); // Prevent default form submission

            // Create a FormData object to easily construct the request payload
            const formData = new FormData(form);

            // Send the form data to the server using fetch API
            fetch('submit.php', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.text(); // Or response.json() if your server returns JSON
            })
            .then(data => {
                // Handle the successful response from the server
                responseMessage.textContent = data;  // Show message from server
                responseMessage.style.display = 'block'; // Make the response message visible
            })
            .catch(error => {
                // Handle errors that occurred during the fetch request
                responseMessage.textContent = 'An error occurred: ' + error;
                responseMessage.style.display = 'block';
            });
        });


        showStep(currentStep); // Initialize the form
    </script>

</body>
</html>
```

```php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Sanitize and validate input data (important for security!)
    $firstName = htmlspecialchars(trim($_POST["firstName"]));
    $lastName = htmlspecialchars(trim($_POST["lastName"]));
    $email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
    $address1 = htmlspecialchars(trim($_POST["address1"]));
    $address2 = htmlspecialchars(trim($_POST["address2"]));
    $city = htmlspecialchars(trim($_POST["city"]));
    $phone = htmlspecialchars(trim($_POST["phone"]));
    $additionalNotes = htmlspecialchars(trim($_POST["additionalNotes"]));

    // Perform validation checks
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "Invalid email format.";
        exit;
    }

     if (empty($firstName) || empty($lastName) || empty($email) || empty($address1) || empty($city) || empty($phone)) {
        echo "All required fields must be filled in.";
        exit;
    }


    // Process the data (e.g., store in a database, send an email)
    // For demonstration purposes, we'll just display the received data

    echo "<h2>Form Submission Received:</h2>";
    echo "<p><strong>First Name:</strong> " . $firstName . "</p>";
    echo "<p><strong>Last Name:</strong> " . $lastName . "</p>";
    echo "<p><strong>Email:</strong> " . $email . "</p>";
    echo "<p><strong>Address Line 1:</strong> " . $address1 . "</p>";
    echo "<p><strong>Address Line 2:</strong> " . $address2 . "</p>";
    echo "<p><strong>City:</strong> " . $city . "</p>";
    echo "<p><strong>Phone Number:</strong> " . $phone . "</p>";
    echo "<p><strong>Additional Notes:</strong> " . $additionalNotes . "</p>";

    // In a real-world application, you would replace the above echo statements
    // with database insertion or email sending logic.
    // Example (requires database connection):
    /*
    $servername = "localhost";
    $username = "your_username";
    $password = "your_password";
    $dbname = "your_database";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);

    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $sql = "INSERT INTO form_data (firstName, lastName, email, address1, address2, city, phone, additionalNotes)
    VALUES ('$firstName', '$lastName', '$email', '$address1', '$address2', '$city', '$phone', '$additionalNotes')";

    if ($conn->query($sql) === TRUE) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }

    $conn->close();
    */


} else {
    echo "Invalid request.";
}
?>
```
👁️ Viewed: 11

Comments