0

I am using AJAX to send a POST request to a Flask route, but I don't know how to get the post data in a format I can read.

My route looks like this:

@app.route("/sendinvites", methods=["POST"])
@login_required
def sendinvites():
    print(request.get_data("emails"))
    return jsonify("done")

My AJAX looks as:

$.ajax({
    type: "POST",
    dataType: "json",
    url: "/sendinvites",
    data: { emails : emails, usernames: usernames  },
    success: function(data) {
      console.log(data)
    }
  });

An example of the data sent in the emails variable is:

0: Object { id: undefined, username: "me@mydomain.com" }

An example of the output from the route is:

b'emails%5B0%5D%5Busername%5D=me%40mydomain.com'

Does anyone know how I can get the post data into a dictionary object so it is easier to process?

OptimusPrime
  • 777
  • 16
  • 25

1 Answers1

0

There are many ways to do this, but first, verify that the request contains a valid JSON.

  1. request.get_json()
request.get_json(silent=True)

With silent=True set, the get_json function will fail silently when trying to retrieve the JSON body. By default, this is set to False.

  1. jsonify(request.json)

This will return the entire request object. You'll have to extract the required part by specifying the key posted while sending the request in your ajax code.

Refer this for Flask part, thread

Refer this for Ajax part, thread

saintlyzero
  • 1,632
  • 2
  • 18
  • 26