Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Flask not receiving AJAX post? [duplicate]

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

like image 819
M.Johanson Avatar asked Mar 11 '23 23:03

M.Johanson


2 Answers

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

like image 40
Ivan Avatar answered Mar 16 '23 03:03

Ivan


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.

like image 50
Vishvajit Pathak Avatar answered Mar 16 '23 02:03

Vishvajit Pathak