0

I make this HTTP POST Request using jQuery.

function getData() {

    const data = JSON.stringify({
        "test_id": "1"
    });

    jQuery.post('/getData', data, function (response) {
        alert("success");
        console.log(response)

    }, "json");
}

When I receive the request in Python, when I try to print request.data, the string is empty.

When I attach the debugger, I see that data are under form (request.form).

How can I make them accessible from request.data ?

Thanks in advance

6
  • You need to set content type header if you send json. Default is application/x-www-form-urlencoded. To send form encoded don't use JSON.stringify Commented Dec 12, 2021 at 21:26
  • what do you use in Python - Flask, Django, other ? Maybe check request.json Commented Dec 12, 2021 at 22:08
  • you are sending to python POST request with test_id=1 but trying to check variable data Commented Dec 13, 2021 at 2:54
  • @diavolic, yes, when i Send the same request from postman, the test_id is in request.data Commented Dec 13, 2021 at 9:45
  • @furas, I use Flask Commented Dec 13, 2021 at 9:45

1 Answer 1

1

You need to send parameters as {} so you could use contentType.

Doc: jQuery.post

    jQuery.post({
        url: "/getData",
        data: data,
        success: function (response) {
            alert("success");
            console.log(response);
        },
        dataType: "json",
        contentType: 'application/json'
    });

Using contentType: 'application/json' you should get it as request.data but also as request.json which can be more useful.


Minimal working code

from flask import Flask, request, render_template_string, jsonify

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
    return render_template_string('''
<!DOCTYPE html>

<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<script>
function getData() {

    const data = JSON.stringify({"test_id": "1"});

    jQuery.post({
        url: "/getData",
        data: data,
        success: function (response) {
            alert("success");
            console.log(response);
        },
        dataType: "json",
        contentType: 'application/json'
    });
}
getData();
</script>
</head>
</html>
''')

@app.route('/getData', methods=['GET', 'POST'])
def get_data():
    print('args :', request.args)
    print('form :', request.form)
    print('data :', request.data)
    print('json :', request.json)
    print('files:', request.files)
    return jsonify(["Hello World"])

if __name__ == '__main__':
    #app.debug = True 
    app.run()  

Result:

args : ImmutableMultiDict([])
form : ImmutableMultiDict([])
data : b'{"test_id":"1"}'
json : {'test_id': '1'}
files: ImmutableMultiDict([])
Sign up to request clarification or add additional context in comments.

Comments

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.