0

Ajax requests are all new to me. I want to send data from a webpage to my Flask backend using an Ajax request but nothing shows up in the backend:

This is my request:

  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);
  }

In the google chrome console the request and the data are showing up correctly, something like:

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

My backend is:

@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)

and nothing shows up in the terminal but:

request.method == GET
ImmutableMultiDict([])

(Not a single time in the html page I say "GET" request) Do you have any idea what's wrong with it ?

Santeau
  • 839
  • 3
  • 13
  • 23

1 Answers1

0

The solution is simple.

Depending on which method is used (POST, GET, PUT, ...), data is submitted different
When using POST for example, data is packed as "Form data" and can be accessed by reading request.form

When sending a GET request though, data is not submitted as "Form data", but as URL arguments instead, which can be accessed by reading request.args

You can obtain more about request data here in the documentation: https://flask.palletsprojects.com/en/1.1.x/quickstart/#accessing-request-data

Edit: After reading the question again, I just realised the "POST" in your Code.
The request might be interpreted as GET, as the form data is not correctly formatted. The data you are sending must be in a format like field_name=value,...
Check this post for an example: https://stackoverflow.com/a/9713078

DarthVader
  • 192
  • 4
  • 16
  • Thank you for your answer but it doesn't solve my problem since I already use request.form and was wondering why am I not getting any result – Santeau May 26 '20 at 16:51
  • You are using request.form, but you should read from request.args - as your request uses the GET method due to the bad formatted request – DarthVader May 27 '20 at 11:50