Send variables from an HTML form to a Python file

To send variables from an HTML form to a Python file, you can use a combination of HTML, JavaScript, and a server-side script (in this case, Python) to handle the form submission. Here’s a basic example:

HTML Form (index.html):

<!DOCTYPE html>
<html>
<head>
    <title>HTML Form</title>
</head>
<body>
    <h2>HTML Form</h2>
    <form id="myForm" action="submit_form.py" method="post">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name"><br><br>
        <label for="email">Email:</label>
        <input type="text" id="email" name="email"><br><br>
        <button type="submit">Submit</button>
    </form>

    <script>
        // JavaScript to handle form submission
        document.getElementById("myForm").addEventListener("submit", function(event) {
            event.preventDefault(); // Prevent default form submission

            // Get form data
            var formData = new FormData(this);

            // Send form data to Python script using fetch API
            fetch('submit_form.py', {
                method: 'POST',
                body: formData
            })
            .then(response => response.text())
            .then(data => {
                console.log(data); // Log response from Python script
                // Handle response as needed
            })
            .catch(error => {
                console.error('Error:', error);
            });
        });
    </script>
</body>
</html>

Python Script (submit_form.py):

#!/usr/bin/env python3

import cgi

# Get form data from CGI parameters
form = cgi.FieldStorage()

# Get values of form fields
name = form.getvalue('name')
email = form.getvalue('email')

# Process form data (e.g., save to a file, send email, etc.)
# For demonstration purposes, print form data
print(f"Name: {name}")
print(f"Email: {email}")

In this example:

  • The HTML form (index.html) sends form data to submit_form.py when submitted.
  • JavaScript code listens for the form submission event, prevents the default form submission behavior, and sends form data to the Python script using the Fetch API.
  • The Python script (submit_form.py) uses the CGI module to parse form data received from the HTML form and prints the values of form fields.

Note: Make sure your server supports executing Python scripts (e.g., using CGI or a web framework like Flask or Django). Additionally, ensure that your server is configured to handle form submissions and execute Python scripts properly.

Leave a Reply

Your email address will not be published. Required fields are marked *