2

i have small form. I am trying to save form data and print at the same time. its working fine but the issue is I main form is not returning to home page after click on submit button. below is my code

Form

<!DOCTYPE html>
<html>
<head>
    <title>Save and Print Form Data</title>
</head>
<body>
    <form id="myForm" action="process.php" method="post">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" required><br><br>
        
        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required><br><br>
        
        <button type="submit">Save and Print</button>
    </form>
   




    <script>
        // JavaScript to handle form submission and printing
        document.getElementById('myForm').onsubmit = function() {
            // Open a new window to display the print view
            var printWindow = window.open('', '_blank');
            
            // Submit the form to process.php
            this.target = '_blank';
            
            // After submission, close the print window after a delay (adjust timing as needed)
            setTimeout(function(){
                printWindow.close();
            }, 5000); // 5000 milliseconds (5 seconds) delay to allow printing
            
            return true;
        };
    </script>

</body>
</html>

Here is process.php file

<?php
// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Retrieve form data
    $name = $_POST['name'];
    $email = $_POST['email'];
    
    // Insert data into MySQL database (assuming you have a table 'users' with columns 'name' and 'email')
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "aaa";
    
    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    
    // SQL query to insert data
    $sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
    
    if ($conn->query($sql) === TRUE) {
        // Data inserted successfully
     
        
        // Print the data immediately after saving (you can customize the print view as needed)
        echo "<h2>Print Preview</h2>";
        echo "<p>Name: $name</p>";
        echo "<p>Email: $email</p>";
        
        // Add a button to trigger printing
        echo "<button onclick='window.print()'>Print</button>";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
 
    $conn->close();
}
?>

i tried header

header("location: ../padm.php");    
exit;

but instead of form page, its sending print page to header location

0

Browse other questions tagged or ask your own question.