The ajax request does not support this method (the keydown event is only active during debugging)

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.

Answer №1

By hitting enter in the sole input field of a form, you trigger a form submission that sends a POST request to /, an invalid method for that route. Instead of relying on a keydown event, consider attaching a submit handler to the form. Additionally, there is no need to use multiple DOMContentLoaded event handlers.

document.addEventListener('DOMContentLoaded', function()
{
    document.querySelector('form').addEventListener("submit", function(event)
    {
        event.preventDefault();
        do_ajax();
    });
    document.getElementById("btn-post").addEventListener("click", do_ajax);
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to retrieve data from a jQuery AJAX call when it returns?

function isNewUsername(str){ var result; $.post('/api/isnewusername', {username:str}, function(data) { result = data.result; }, "json"); return result; } I am encounte ...

Retrieve the variable only once a response has been received from the POST request

Is there a way to update a variable in my component only after receiving a response from a POST request? Here is the code in component.ts: formSubmit() { this.sent = this.submitProvider.sendByPost(this.form); this.formSent = this.submitProvider.f ...

Choose the date that is exactly 48 hours from now

I need to implement a date picker that shows today's date and the next 2 days in a select component. Can this be achieved using JavaScript and jQuery? While I came across a similar post on the topic, I specifically want it to work with a date picker: ...

commenting system through ajax across multiple web pages

Experimenting with the webcodo comment system has led me to this URL: Database table: "comments" CREATE TABLE IF NOT EXISTS `comments` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(40) NOT NULL, `email` varchar(60) NOT NULL, `comment` te ...

Every time I attempt to reuse my components, they keep piling up on top of each other

I'm facing an issue where I need to reuse components I've created multiple times while rendering dynamic content. However, when I attempt to render them, they end up stacking on top of each other in the same position. Each time I render ...

React Bootstrap always displays tooltips

I have integrated react-bootstrap into my project. I am currently attempting to keep a tooltip always displayed, but I am facing some challenges in achieving this. Below are the approaches I have tried so far: <Card style={{width: '10rem'}} ...

"Enhancing website performance with JavaScript by leveraging DOM innerHTML scrollHeight

Here is a two-part question I have: The first part of the question: test A: t1 = new Date().getTime(); for (i=0; i<205; i++) { document.getElementById("divTest").innerHTML = sText; } t2 = new Date().getTime(); ...

Managing the re-triggering of a function within useEffect upon the user clicking the "Back Button" in a React application

Is there a way to prevent the loadUserPosts() function from being called again when the user clicks the 'back button' on their browser? It seems like the isLogged useState is being changed when the back button is clicked. The loadUserPosts funct ...

Utilizing the output of a callback function to execute res.render in a NodeJS application

Currently, I am utilizing oracledb for node in order to retrieve data from the database. Once the data is fetched, my goal is to transmit it to the client side using render() in express JS. Below is an example of the code structure: config.js module.expo ...

Invoke React Component Function using onclick in dangerouslySetInnerHTML

I'm new to React and I have a contenteditable div with dangerouslySetInnerHTML as the child, for formatting user input at runtime. When a specific span is clicked inside the HTML, I want to update a variable in the parent component using setState. Is ...

The password-protected HTML blog remains hidden until the correct entry is entered into the password box, causing

After successfully creating a password redirect page where entering the correct password redirects you to another URL (psswrdtest.tumblr.com with the password as correctpsswrd, redirecting to google.com*), I attempted to improve it by making the password p ...

Tips for selecting array [0] and turning it into a clickable link with JavaScript

My challenge lies in redirecting to a different URL when the user clicks on <a href="javascript:void(0)">Hotel Selection</a>. Below is my current progress. Grateful for any assistance! <div id="menu"> <ul> <li class= ...

Issue with AdminLite 2.4.0 data table functionality malfunctioning

Check out this template that I'm using. I've copied all the contents for the bower_components and dist folders, and made sure to link and require everything properly. There are no 404 errors, only status code 200. Here is a snippet of my code: ...

Having trouble retrieving data passed between functions

One of my Vue components looks like this: import '../forms/form.js' import '../forms/errors.js' export default{ data(){ return{ form: new NewForm({ email: '&apos ...

When I attempted to use jQuery to access the innerHTML of list items, I encountered the issue of it returning as Undefined

For my grocery list application created with Angular 4, I need the user to click on an item and have it added to the bookmarked section. Despite using jQuery to access the innerHTML of the li when hovered over, the value keeps returning as "undefined." In ...

Arranging grid elements in Material-UI

Currently, I am in the process of transforming a JavaFx window into a web application using React.js & Material Ui. The goal is to replicate the appearance and functionality of the original JavaFx application as closely as possible. The layout of the wind ...

Canceling text as soon as the search input is entered in Vue.js

When I use the search input box, the last text I typed in gets cancelled. Can anyone help me with this issue? <input class="navbar-searchbar__text-field" type="search" :value="searchQuery" name=" ...

Can Node.js endpoints effectively handle the garbage collection of new class instances?

Just diving into node.js I'm currently dealing with a lengthy and messy function that constructs a CYPHER query for Neo4j. I am considering transforming it into a class, complete with methods, along with a corresponding mocha spec. The expected usag ...

What is the best way to access this variable within a json object?

On my website, I am working with a page called insert.php that returns a JSON array containing $my_variable to another page called form.php. Although I can view the array in the response section of my Firebug console, I am unsure how to access it in form. ...

Error: The validation of a JSON request failed as schema.validate is not a recognized function

As a beginner, I am currently immersed in a node.js API authentication tutorial. Everything was going smoothly until I had to refactor my code into separate files. Now, every time I send a JSON request via Postman, I keep encountering the error message "Ty ...