Joy Dutta Joy Dutta - 7 days ago 7
JSON Question

Sending JSON to Flask with jQuery gives error

I want to use jQuery to send JSON data to a Flask route. However,

request.get_json()
gives an error. Why doesn't this work?

my_array = {"student_data":{"actual_data":12,"sheet_data":23,"age":"20"},"teacher_data":{"actual_data":193,"sheet_data":203,"age":"40"},"school_data":{"actual_data":593,"sheet_data":29,"age":"49"}};
$.ajax({
url: '/submit_method',
data: my_array,
contentType: 'application/json; charset=utf-8',
type : 'GET',
async: 'false',
success: function (serverResponse) {
}
});




@app.route('/submit_method', methods=['GET'])
def submit_method():
k = request.get_json()
return ''

Answer

You have to use POST method instead of GET.

    @app.route('/submit_method', methods=['GET'])
    def submit_method():
        k = request.data     # gets request body in form of dictionary
        return json.dumps(k) # converts dictionary to json


   $.ajax({
     url: '/submit_method',  data:   JSON.stringify(my_array),  
     contentType:"application/json; charset=utf-8", 
     type : 'POST', async: "false",  success  : function (serverResponse) {}});
Comments