4

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 :)

Joe Doherty
  • 3,778
  • 2
  • 31
  • 37
M.Johanson
  • 51
  • 2
  • 3

3 Answers3

4

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.

Vishvajit Pathak
  • 3,351
  • 1
  • 21
  • 16
3

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

Zixian Cai
  • 945
  • 1
  • 10
  • 17
1

If you data object in Ajax is json then you can use request.get_json()

If it is form data of key value then you can request.form.get('data') but your ajax should be

$('#button').click(function() {
$.ajax({
   url:"/",
   type: 'POST',
   data: {data: 'mystring'},
Atul Mishra
  • 298
  • 2
  • 11