Transmit information to Flask server using an AJAX POST call

I'm completely new to Ajax requests. I'm trying to send data from a webpage to my Flask backend using an Ajax request, but I can't get anything to show up in the backend:

Here is the request code I am using:

  function confirm() {
    const xhttp = new XMLHttpRequest();
    const data = document.getElementById("tableID");
    xhttp.open("POST", "app.py");
    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhttp.send(data);
    console.log(xhttp);
    console.log(data);
  }

When viewing in the Google Chrome console, the request and data appear correctly like this:

<table id="tableID">
    <tbody>
        <tr>...</tr>
        <tr>...</tr>
        <tr>...</tr>
    </tbody>
</table>

This is how my backend looks:

@app.route('/admintools', methods=["POST", "GET"])
def admintools():
    tracks = observed_tracks(get_tracks())
    if request.method == "POST":
        print("request.method == POST")
        print(request.form)
    if request.method == "GET":
        print("request.method == GET")
        print(request.form)
    return render_template("tools/admintools.html", tracks=tracks)

However, nothing appears in the terminal except for:

request.method == GET
ImmutableMultiDict([])

(I never mention "GET" request in the HTML page at all) Any ideas on what the issue might be?

Answer №1

The solution at hand is quite straightforward.

Depending on the method used for data submission (POST, GET, PUT, etc.), the approach varies.
For instance, when utilizing POST, data is encapsulated as "Form data" and can be retrieved by accessing request.form

Conversely, with a GET request, data isn't transmitted as "Form data" but as URL parameters instead, which are accessible through request.args

Further insights concerning request data can be found in the documentation:

Edit: Upon reviewing the query again, I've come to notice the presence of "POST" in your Code.
This indicates that the request might actually be interpreted as a GET due to incorrect formatting of form data. Ensure that the data being sent follows a format like field_name=value,...
Refer to this post for an example:

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

Making asynchronous requests using AJAX

$.ajax({ async:false, url: "ajax/stop_billed_reservation_delete.php", type: "POST", dataType : "json", data : { "rid" : <?php echo $_GET['reservationId']; ?> }, success: function(result){ ...

How can I change the attributes of icon().abstract.children[0] in the fontawesome-svg-core api?

The issue at hand: The icon() function within the fontawesome-svg-core API is setting default properties for SVG children elements that require custom modifications. My objective: The outcome of the icon() method is an object with an "html" property, co ...

Why won't my AngularJS Google Maps marker trigger any events?

My issue is with the marker event not working on a UI Google Map. I am using this link. Here is my view setup: <ui-gmap-markers models="mapResult" fit="true" idkey="mapResult.id" coords="'form_geo'" click="'onclick'" events="mapRe ...

What is the process for connecting personalized toggle controls to a checkbox input field?

I have created a custom slide toggle control to enhance the functionality of my checkboxes in the app. You can check out the controls by following this link: http://codepen.io/spstratis/pen/fJvoH Currently, I am looking for a way to connect these switche ...

The enigmatic jQuery AJAX glitch is craving additional arguments

My website uses jQuery's ajax function to handle user signups. Despite using similar code throughout the site, I encountered an error while trying to execute the code below: Error Message: uncaught exception: [Exception... "Not enough arguments" nsr ...

Troubleshooting session flash issues in Laravel

I have been working on a project that involves moving files from one folder to another on an FTP server. I've set it up so that when the file transfer is completed, a message should appear on the screen. However, I seem to be having trouble with using ...

MXGraph has an issue where edges fail to be redrawn after being moved

Perhaps this question may seem trivial, but I am facing an issue in my code and seeking guidance from the community. I am working on a javascript mxGraph application within Angular7. Specifically, I have modified the ports.html example for my project. Wh ...

Would this be considered an effective way to utilize JQuery's queues?

Currently, I am working on a webpage that displays a list of users and I need to retrieve icons showing their Skype status from . However, I have encountered issues with the calls to mystatus.skype.com failing when sent simultaneously. To address this pr ...

Guide on integrating database information into an array with Vue.js

I'm having trouble retrieving data from Firestore and applying it as my array. I expect to see objects in the console but nothing is showing up. Should the method be called somewhere in the code? My method created() is functioning, but only when I han ...

Headers with a 3 pixel stroke applied

I have a design on my website that includes a 3px stroke around the header text to maintain consistency. I don't want to use images for this due to issues with maintenance and site overhead. While I know about the text-stroke property, browser suppor ...

Utilizing Django to determine the appropriate view based on whether it is a GET request or an AJAX POST method

In my Django project, I have a view that serves different purposes depending on whether the request method is GET or POST. When it's a GET request, the view simply renders the page for the user. On the other hand, when it's a POST request, I use ...

Additional headers are included in the Access-Control-Request-Headers

I have been struggling to include a customized header in my angular js GET request like so: $http({ method : 'GET', url : s, headers : { "partnerId" : 221, "partnerKey" : "heeHBcntCKZwVsQo" } ...

URL-based authentication using Passport.js

I am currently working on my app using Express JS and Passport JS. My goal is to allow a new user to automatically log in once by accessing a specific URL. I have the ability to retrieve the user information from the database based on the URL provided, re ...

The Angular Material layouts demonstration is experiencing technical difficulties

I'm attempting to run the Angular Material grid layouts demo titled Flex Percent Values, which can be accessed here. Here are some snippets from my HTML code: <head> <meta charset="UTF-8"> <meta name="viewport" content="initial-sc ...

How to retrieve values in each element using jQuery

I am facing an issue with a foreach loop that generates multiple input boxes containing various attributes such as id, quantity, and color. My goal is to allow the user to update the quantity of all items within the foreach loop by clicking on a single but ...

Customizing the data received from an AJAX request before displaying it

I'm working on a subscription form using jQuery/ajax and I want to only show the div#alertmsg and the second "p" tag in the success function. The content I need to display will vary based on whether the email already exists in the database. Is there ...

What are the best ways to maximize a web worker's ability to handle multiple tasks at once

I'm currently working on implementing a Web-Worker to handle its state while also managing multiple asynchronous requests. worker.ts file let a =0; //state of the worker let worker=self as unknown as Worker; worker.onmessage =(e)=>{ console ...

How to retrieve the object's property with the highest numerical value using JavaScript

My current object is structured as follows: const obj = { happy: 0.6, neutral: 0.1, said: 0.3 } I'm trying to determine the best method to retrieve the property with the highest value (in this case, it would be "happy"). Any suggestions o ...

Update the CURLOPT_URL parameter to accept user input

As someone new to coding, I have a question about using the CURLOPT_URL function in PHP. How can I input a NIK number and retrieve data from this URL: ? Any help would be appreciated, thank you! php $curl = curl_init(); curl_setopt_array($curl, [ CU ...

Minimize CPU consumption in your threejs application

I've been working on a project where I'm coding Snake in Threejs (I know there are simpler methods). Everything works smoothly until the snake reaches a certain size, causing CPU usage to spike to 50% or more and freezing the entire browser tab. ...