-1

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 ''
davidism
  • 121,510
  • 29
  • 395
  • 339
Joy Dutta
  • 13
  • 1
  • 5

2 Answers2

0

You have to use POST method instead of GET.

    @app.route('/submit_method', methods=['POST'])
    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) {}});
SaiNageswar S
  • 1,203
  • 13
  • 22
0

The issue is JavaScript has to be converted to a JSON string first, using JSON.stringify. Otherwise Flask will not consider it application/json content type and deny the request with a 400.

$.ajax({
    url: '/submit_method',
    data: JSON.stringify(my_array),
    contentType: 'application/json; charset=utf-8',
    type : 'GET',                         
    async: 'false',
    success: function (serverResponse) {          
    }
});
Steve
  • 1,423
  • 10
  • 13