5

I am attempting to POST data to Flask application. It receives the POST request, but I am not sure how to request the data.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

function Submit() {
    var myData = "this is my data string"

    $.post("/receivedata", function(myData , status){
        alert(status);
    });
}

in Flask:

@application.route('/taskinputjs', methods=['GET', 'POST']) 
@login_required
@roles_accepted('Admin')
def taskinputjs():
    print "taskinputjs..."
    if request.method == 'POST':

        data = request.args.get('myData', None, type=str)
        #data = request.form['myData']

    return render_template('index.html')

It posts, however only "None" is returned for myData

How do I properly request the data?

1

2 Answers 2

18

That's probably because you are not actually sending any data. It should be something like this (jQuery docs):

<button onclick=submit()>Click me!</button>
<script>
function submit() {
    var myData = "This is my data string."
    $.post("/receivedata", {"myData": myData})
}
</script>

and in Flask app:

application.route('/receivedata', methods=['POST'])
def receive_data():
    print(request.form['myData'])

which will output your data in flask console when you click the button: this is my data string

Sign up to request clarification or add additional context in comments.

2 Comments

For some reason, when I tested your code it did not print anything, but maybe is on me. Does your print statement needs parenthesis?
yes, thank you, I edited my answer to work with python3 (previous version worked on python2 only)
1

From my recent research I found that the post request to the flask app needs to be with a data type of json to make it work.

In my case I had to use something like:

var data = {"data": "data"}
$.ajax({
    type: 'POST',
    contentType: 'application/json',
    url: '/isChat',
    dataType : 'json',
    data : JSON.stringify(data),
    success : (data) => {
        console.log('isChat response: ' + data)
    },
    error : (data) => {
        console.log(data)
    }
});

Where in the flask app the post listener should have caught the request with the request.get_json()

@application.route('/isChat', methods=['POST'])
def isChat():

    request_data = request.get_json()

    data = request_data['data']

    # DO SOME WORK ...

    toReturn = {"return": "True"}

    return jsonify(toReturn)

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.