Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery post to Flask, how to request data?

Tags:

flask

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?

like image 306
b_g Avatar asked Dec 04 '22 02:12

b_g


2 Answers

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

like image 83
dkol Avatar answered Dec 06 '22 14:12

dkol


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)
like image 44
Luca C Avatar answered Dec 06 '22 16:12

Luca C