Joy Dutta Joy Dutta - 1 year ago 70
JSON Question

Sending JSON to Flask with jQuery gives error

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

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"}};
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 Source

You have to use POST method instead of GET.

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

     url: '/submit_method',  data:   JSON.stringify(my_array),  
     contentType:"application/json; charset=utf-8", 
     type : 'POST', async: "false",  success  : function (serverResponse) {}});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download