I’m trying to send form field input values using POST, Ajax, Json and Javascript method to wsgiref Python, what problem am I running into with error 500 ? How can I send this data to python to process them without encountering an error, below are the codes (html, javascript and python) ?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta name="description" content=""/>
<meta name="keywords" content=""/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<style>
.input-field input[type=email] + label { color: #455a64 !important; margin-left: 20px; margin-top: 15px; }
.input-field input[type=email] { width: 362px; height: 70px; padding-left: 20px; padding-right: 20px;
border: 1px solid #455a64 !important; box-shadow: 0 0 0 0 #455a64 !important; border-radius: 5px; }
.input-field input[type=email]:focus + label { color: #0d47a1 !important; margin-left: 20px; margin-top: 20px; }
.input-field input[type=email]:focus { border: 1px solid #0d47a1 !important; border-radius: 5px; font-size: 20px; }
</style>
<title>Webstrucs Form</title>
</head>
<body>
<main>
<div class="input-field">
<input id="email" type="email" class="ws_input_email">
<br>
<a class="waves-effect waves-light blue darken-4 btn-large"></a>
</div>
</main>
<script>
const next = document.querySelector(".btn-large")
const text = next.innerHTML = "Seguinte"
next.onclick = function() {
let ws_safe_email = document.querySelector(".ws_input_email").value
const jsonData = {
"ws_safe_email": ws_safe_email
}
const jsonSend = JSON.stringify(jsonData)
const ajax = new XMLHttpRequest()
ajax.open("POST", "http://127.0.0.1:8080/", true)
ajax.setRequestHeader("Content-Type", "application/json")
ajax.send(jsonSend)
}
</script>
</body>
</html>
from wsgiref.simple_server import make_server
# Module name : cgi -> ( https://docs.python.org/3/library/cgi.html#module-cgi )
import cgi, json
def apps(environ, start_response):
# Function -> Capture the request method:
v_mtd = environ["REQUEST_METHOD"]
# Function -> Capture the request form data:
v_inp = cgi.FieldStorage(environ["wsgi.input"], environ=environ)
if v_mtd == "GET":
# Acessa o arquivo static requisitado :
o_file = open("index.html", "r")
# Faz a leitura do arquivo :
s_file = o_file.read()
status = "200 OK"
headers = [("Content-type", "text/html; charset=utf-8")]
start_response(status, headers)
# The returned object is going to be printed
return [str(s_file).encode('utf-8')]
elif v_mtd == "POST":
ws_email_add = v_inp["ws_safe_email"]
v_json = json.dumps(ws_email_add)
return v_json
with make_server("", 8080, apps) as httpd:
print("Serving on port 8080...")
# Serve until process is killed
httpd.serve_forever()