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

Are HTTP GET requests and AJAX calls interchangeable?

I've been curious about this and haven't found a clear answer anywhere else. Is an HTTP GET request asynchronous? If so, what are the main distinctions? I'm not interested in opinions, just concrete answers. My searches have only resulted ...

What is causing the click function to malfunction after selecting a second item?

I'm struggling to understand why my click function isn't functioning properly. You can view the JSFiddle here: http://jsfiddle.net/adbakke/ve9oewvh/ This is a condensed version of my HTML structure: <div class="projectDisplay"></div&g ...

Utilizing custom links for AJAX to showcase targeted pages: a beginner's guide

I am putting the final touches on my website and realized that it may be difficult to promote specific sections of the site because the browser address never changes. When visitors click on links, they open in a div using Ajax coding. However, if I want to ...

How come using a query object as a parameter for .limit() returns an empty array?

I am currently working on a mongoose query setup where I have a custom queryObject containing key-value pairs for specific records. If a key-value pair does not exist in the req.query, it is omitted from the queryObject. Oddly enough, when setting the que ...

"Exploring the process of integrating angular-xeditable into a MeanJS project

I recently attempted to install angular-xeditable from the link provided, but encountered issues while trying to reference the JavaScript files in layout.html after downloading it with bower. According to the documentation, these files should be added auto ...

Customizing the default button in Ant Design Popconfirm to display "Cancel" instead

When the Ant Design Popconfirm modal is opened, the Confirm ("Yes") button is already preselected. https://i.stack.imgur.com/bs7W7.png The code for the modal is as follows: import { Popconfirm, message } from 'antd'; function confirm(e) { c ...

Tips for swapping out text with a hyperlink using JavaScript

I need to create hyperlinks for certain words in my posts. I found a code snippet that does this: document.body.innerHTML = document.body.innerHTML.replace('Ronaldo', '<a href="www.ronaldo.com">Ronaldo</a>'); Whil ...

ASP updatepanel textbox focusing - Working only with breakpoints, not without them

I've encountered a bizarre problem where my code functions perfectly with a breakpoint set, but when I remove the breakpoint, certain parts of the code fail to work. My goal is to have a textbox automatically select all text upon focus; it should foc ...

Issue with the functionality of Material-ui tooltip

I'm exploring the implementation of the material-ui tooltip feature and I am hoping to have it displayed at the top of the element. Despite specifying placement="top", the tooltip still does not appear as intended. You can view a demo of this issue b ...

The function d3.json() does not support googleoverlay

As a newcomer to coding, I am currently working on incorporating the code found at https://bl.ocks.org/mbostock/899711. Instead of using a local .json file, I have opted to read JSON data from a URL. However, I encountered an issue where the LAT and LONG v ...

Embedded UpdatePanels trigger complete page refresh

I am encountering a problem with nested, custom user controls that are causing full page postbacks despite being enclosed within an UpdatePanel. Here is the code for the update panel: <asp:Content ID="mainContentPane" ContentPlaceHolderID="mainContent ...

Issues with JQuery list selectors

Many individuals have raised concerns about selectors in the past, but no matter what I try, my code seems right yet it doesn't work as intended. My situation involves a list of actions that are displayed or hidden when their corresponding "folder" is ...

The integration of query, URL, and body parameters is not working as expected in Seneca when using Seneca

I'm facing some difficulties with Seneca and seneca-web as a beginner. This is the current state of my code: "use strict"; var express = require('express'); var Web = require("seneca-web"); var bodyParser = require('body-parser' ...

Exploring nested static properties within TypeScript class structures

Check out this piece of code: class Hey { static a: string static b: string static c: string static setABC(a: string, b: string, c: string) { this.a = a this.b = b this.c = c return this } } class A { static prop1: Hey static ...

Avoid invoking a TypeScript class like a regular function - _classCallCheck prevention

I am currently developing a TypeScript library that needs to be compatible with all versions of JavaScript. I have noticed that when calling a class in TS without using new, it does not compile properly, which is expected. In ES6/Babel, a class automatica ...

What is the best way to load an ExtJS combobox with a JSON object that includes an array

After retrieving the following JSON from the backend: { "scripts": [ "actions/rss", "actions/db/initDb", "actions/utils/MyFile", "actions/utils/Valid" ], "success": true } The JSON data is stored as follows: t ...

Verifying the presence of a value within an SQL table

I am currently working on developing a bot that requires me to save the commandname and commandreply in a database. Right now, I am using mySQL Workbench for this task. My goal is to verify if the commandname provided by the user already exists in the tab ...

What is the process for storing form data into a text file?

Despite seeing similar questions in the past, I am determined to get to the bottom of why this code isn't functioning as expected. My goal is to input form data into a .txt file using a post request. While I lack extensive knowledge of PHP, I am pieci ...

It appears that Vivus JS is having difficulty animating specific <path> elements

I've been experimenting with the Vivus JS library, which is fantastic for animating paths such as drawing an image. However, I'm facing an issue where my SVG icon should animate to a 100% line-width, but it's not working as expected. Interes ...

What could be causing my .load() function to fail when attempting to target a specific div element?

My goal is to retrieve and display a div tag from another aspx page within my container div. Here is the jQuery code: function GetDocumentInfo(url) { $('MyContainer').load(url + ".otherdiv"); } This operation is triggered by a click event. ...