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?
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With