I've encountered a strange issue with an AJAX request.
The server-side code in app.py
:
#### app.py
from flask import Flask, request, render_template
app = Flask(__name__)
app.debug = True
@app.route("/myajax", methods=['GET', 'POST'])
def mypostajaxreq():
print(request.form)
if request.method == "POST":
name = request.form["name"]
return " Hello " + name
else:
return "Just Hello"
@app.route("/")
def index():
return render_template("indexlistener.html")
if __name__ == "__main__":
app.run()
The content of indexlistener.html
:
<!DOCTYPE html>
<html>
<head>
<title>Practice AJAX</title>
<script type="text/javascript" src = "/static/js/myajaxrequestlistener.js"></script>
</head>
<body>
<form method="post">
<label>Name:<input type="text" id="name" value="" /></label>
<button type="button" id="btn-post">Click</button>
<div id="result"></div>
</form>
</body>
</html>
The contents of myajaxrequestlistener.js
file:
function do_ajax ()
{
var req = new XMLHttpRequest();
var result = document.getElementById('result');
req.onreadystatechange = function()
{
if(this.readyState == 4 && this.status == 200) {
result.innerHTML = this.responseText;
}
}
req.open('POST', '/myajax', true);
req.setRequestHeader('content-type', 'application/x-www-form-urlencoded;charset=UTF-8');
req.send("name=" + document.getElementById('name').value);
};
document.addEventListener('DOMContentLoaded', function()
{
document.getElementById("btn-post").addEventListener("click", function()
{
do_ajax();
})
})
document.addEventListener('DOMContentLoaded', function()
{
document.addEventListener("keydown", function(event)
{
if(event.key === "Enter")
{
do_ajax();
}
})
})
When clicking the button, everything functions as expected. However, when pressing Enter
, it returns an Error 405: Method not allowed
. This is puzzling to me as I've confirmed that the listener for the keydown event triggers and works with the debugger. Strangely enough, the issue only arises when pressing Enter
directly. I'm suspecting a problem with the listener, but I can't comprehend why it's happening. Moreover, the logic behind the error code (405
) baffles me: in theory, this error should occur only if the route on the server side doesn't accept the requested method. In my case, both GET and POST methods are accepted, and I'm exclusively sending POST requests from the webpage. As a novice in web development, any insights would be greatly appreciated. Thank you.