1

I am using AJAX to POST a JSON string to Python Flask but the string doesn't seem to get passed to the flask app.

scoresaver.addEventListener('click', function(ev){
    if (scorestate==1) {
      var pdata = {'uname':uname, 'score':score.saved}
      $.ajax({
        type: 'POST',
        url: '/',
        data: JSON.stringify(pdata),   
        })
      score.saved=null;
      scorestate=0;
    }
});

On clicking a button the above code is supposed to "send" the JavaScript obj to Python Flask as a string. I have verified that JSON.stringify (pdata) produces the string I require.

@app.route("/", methods=["GET", "POST"])
def index():
    if request.method == "POST":

        print(request.get_json())

        return render_template("index.html")

    else:
        return render_template("index.html")

This is my code in my Flask application print (request.get_json() comes out to be None.

1 Answer 1

1

Please add this key to your ajax call and try again:

contentType: "application/json",

The request's get_json() populates only if the content-type is set to be JSON.

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

1 Comment

This was was the exact cause of the problem. Thanks for helping out

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.