I have run into a problem with my javascript/python script. What I am trying to do is pass a string to python flask so I can use it later. When I click the button to send the string, there are no errors but nothing happens. I am basically a self taught coder so I apologise if my script it not properly formatted!
Javascript:
$('#button').click(function() {
$.ajax({
url:"/",
type: 'POST',
data: data,
...
Python Flask:
from flask import Flask
from flask import request
from flask import render_template
app = Flask(__name__)
@app.route('/', methods=['POST', 'GET'])
def home():
if request.method == "POST":
string = request.args.get(data)
print(string)
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
I want to be able to see the string printed to either the console or the command prompt, I assume print() is the right way to do this? Any help would be welcome, thank you :)
What you want is in request.data
.
request.args
contains parameters in the URL.
Check this out for more details. http://flask.pocoo.org/docs/0.11/api/#incoming-request-data
You can make an ajax POST request like this:
$.ajax({
url: "/",
method: "POST",
data: { paramter : value },
});
The data send over this POST request can be accessed in flask app withrequest.form['parameter']
If you are sending raw json data, you can access the data by request.json['parameter']
$.ajax({
url: "/",
method: "POST",
data: JSON.stringify("{'paramter': 'value'}"),
contentType: 'application/json;charset=UTF-8'
});
And this should work.
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