ajax post to flask code example
Example 1: get post request data flask
@app.route('/form-example', methods=['GET', 'POST']) #allow both GET and POST requests
def form_example():
if request.method == 'POST': #this block is only entered when the form is submitted
language = request.form.get('language')
framework = request.form['framework']
return '''<h1>The language value is: {}</h1>
<h1>The framework value is: {}</h1>'''.format(language, framework)
return '''<form method="POST">
Language: <input type="text" name="language"><br>
Framework: <input type="text" name="framework"><br>
<input type="submit" value="Submit"><br>
</form>'''
Example 2: how to get data in flask from ajax
from flask import *
app = Flask(__name__)
@app.route("/", methods=["POST", "GET"])
def home():
return render_template("index.html")
# This function gets param1 from url yourflaskroot/getdata
# which was the url set in ajax code and return param1 back to it
# you can write a simple ajax code to test it out
@app.route("/getdata")
def myFunction():
# Fill parameter with the argument sent from ajax
parameter = request.args.get('param1')
# Send parameter as an argument to ajax
return f"the returned data from python is : {parameter}"
if __name__ == "__main__":
app.run(debug=True)