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)
    }
5
  • related: jQuery posting JSON, Send JSON data with jQuery, and Send JSON Object with Ajax? Commented May 30, 2019 at 9:31
  • I am not using jQuery Commented May 30, 2019 at 9:37
  • I know. They're related, not duplicates. Check out the last one, though. Commented May 30, 2019 at 9:39
  • Thanks but the last one doesn't show what to do at the Flask end Commented May 30, 2019 at 9:59
  • I think you should use the jsonify function to return json response from your flask api Commented May 30, 2019 at 10:21

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.