JSFiddle - React, Tailwind, and code Playground

by Chris

HTML

<!DOCTYPE html>
<html>
<head>
    <title>Simple Interaction</title>
</head>
<body>
    <form action="process.py" method="post">
        Enter something: <input type="text" name="user_input" />
        <button type="submit">Submit</button>
    </form>
    <div id="result"></div>
    <script>
        const form = document.querySelector("form");
        form.addEventListener("submit", (event) => {
            event.preventDefault(); // Prevent default form submission
            fetch("process.py", {
                method: "POST",
                body: new FormData(form)
            })
            .then(response => response.text())
            .then(data => {
                document.getElementById("result").innerHTML = data;
            })
            .catch(error => console.error(error));
        });
    </script>
</body>
</html>

JavaScript

import cgi

def process(data):
  # Replace with your actual Python logic
return f "You entered: {data}"

def main():
  form = cgi.FieldStorage()
data = form.getvalue("user_input")
if not data:
  return "No data received."
result = process(data)
print("Content-type: text/html\n\n") # Set output format
return result

if __name__ == "__main__":
  print(main())