0

I try to send json data from JavaScript to the flaskapp. But the json data sent from JavaScript is not accepted by the flask, the request is null, where is the wrong?

Here is my flask code.

@main.route('/getjson', methods = ['GET', 'POST'])
def getjson():
    a = request.json
    return jsonify(user = a)

Here is my javascript code.

$(function(){
    $("#test").click(function(){
        $.ajax({
            url: "{{ url_for('main.getjson') }}",
            type: "POST",
            data: JSON.stringify({
                "n1": "test1",
                "n2": "test2",
                "n3": "test3"
            }),
            dataType: "json",
            success: function(data){
                var a = data.user
                var texthtml = "<p>" + a + "</p>"
                $("#result").html(texthtml)
            }
        });
    });
});

The data returned on the page is always null. Request.arg.get also does not work.

Lee Andy
  • 3
  • 2

1 Answers1

1

Flask's request.json requires the application/json content type but $.ajax sets application/x-www-form-urlencoded by default. Set the content type when making the request.

$.ajax({
        url: "{{ url_for('main.getjson') }}",
        type: "POST",
        data: JSON.stringify({
            "n1": "test1",
            "n2": "test2",
            "n3": "test3"
        }),
        contentType: "application/json",
        dataType: "json",
        success: function(data){
            var a = data.user
            var texthtml = "<p>" + a + "</p>"
            $("#result").html(texthtml)
        }
    });

Alternatively, send the object itself, without JSON.stringify():

$.ajax({
        url: "{{ url_for('main.getjson') }}",
        type: "POST",
        data: {
            n1: "test1",
            n2: "test2",
            n3: "test3"
        },
        dataType: "json",
        success: function(data){
            var a = data.user
            var texthtml = "<p>" + a + "</p>"
            $("#result").html(texthtml)
        }
    });

This will send the data as form-encoded, so you would use request.form in Flask to read it.

The dataType is the type of data that you expect to receive from server while the contentType is the type of data that you send to the server.

See:

davidism
  • 121,510
  • 29
  • 395
  • 339
Krzysiek
  • 7,895
  • 6
  • 37
  • 38