2

I am unsure how to extract data from an Ajax request from my Javascript code in a python application in Flask. My Ajax request does not use jQuery.

I have tried using request.form.get() and request.get_json() in my Python code but both produce a None value.

@app.route("/", methods=["GET", "POST"])
def index():
    if not request.get_json() == None: 
        print(request.get_json())
        name = request.get_json()
        session["name"] = name.user
    return render_template("index.html", channels=channels)

In my Javascript code I perform a simple Ajax request:

    if(localStorage.getItem("user")) {
        document.querySelector("#logout").addEventListener("click", () => {
            localStorage.removeItem("user");
        })

        const request = new XMLHttpRequest();
        request.open("POST", "/")
        user = JSON.stringify(localStorage.getItem("user"))
        request.send(user)
    }
M. Alex
  • 673
  • 5
  • 26
  • related: [jQuery posting JSON](https://stackoverflow.com/questions/5570747/jquery-posting-json), [Send JSON data with jQuery](https://stackoverflow.com/questions/6587221/send-json-data-with-jquery), and [Send JSON Object with Ajax?](https://stackoverflow.com/questions/6418220/javascript-send-json-object-with-ajax) – Matt Ellen May 30 '19 at 09:31
  • I am not using jQuery – M. Alex May 30 '19 at 09:37
  • I know. They're related, not duplicates. Check out the last one, though. – Matt Ellen May 30 '19 at 09:39
  • Thanks but the last one doesn't show what to do at the Flask end – M. Alex May 30 '19 at 09:59
  • I think you should use the [`jsonify`](http://flask.pocoo.org/docs/1.0/api/#flask.json.jsonify) function to return json response from your flask api – Kunal Mukherjee May 30 '19 at 10:21

2 Answers2

1

The data should be coming in request.get_data() not in request.get_json()

refer request.get_json & request.get_data for more info

Naveen Siva
  • 202
  • 1
  • 9
  • 1
    If your request type is application/json it will come under request.get_json() in your case you haven't mentioned any request type it should be coming in request.get_data() – Naveen Siva May 30 '19 at 10:22
0

If i understand it clearly you don't want to send the whole dictionary like ('user':'value') only the value.

In this case request.get_data() works just fine in this case:

from flask import Flask, request
app = Flask(__name__)

@app.route('/', methods=["GET","POST"])
def index():
    data = open('index.html').read()
    print request.get_data()
    return data

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8080)

index.html is a simple page with a button which triggers the following javascript:

var request = new XMLHttpRequest()
request.open("POST","/", true)
var send_data = "Hello World"
request.send(send_data)
mibognar
  • 74
  • 5