0

So I have this simple python script running on Flask that I'd like to pass variables to with an ajax jQuery request. I might be missing something obvious but I can't get it to work properly.

@app.route('/test', methods=['GET', 'POST'])
def test():
    my_int1 = request.args.get('a')
    my_int2 = request.args.get('b')
    my_list = [my_int1, my_int2]
    with open('my_csv.csv', 'wb') as myfile:
        wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
        wr.writerow(my_list)
    return '' #does one have to have an return even tho it is just a script?

So, above will work fine when just passing parameters to the URL field: http://127.0.0.1:5000/test?a=10&b=25 however, trying this in the chrome console will not yield any output at all:

$.ajax({
  method: "POST",
  url: "127.0.0.1:5000/test",
  data: {a: 10, b: 25},
  dataType: "script"
});

What am I missing and why does the above jquery ajax request not work? $.ajax is not a function(…)

2
  • I think, there is a problem with your jquery reference in that HTML file. Commented Sep 2, 2016 at 18:02
  • Check the response in a browser. Maybe some header is missing, like the allow access control Commented Sep 2, 2016 at 18:15

3 Answers 3

1

Please, try with the following code and let me know if that's what you are looking for:

from flask import Flask, request
import csv

app = Flask(__name__)


@app.route('/test', methods=['GET', 'POST'])
def test():
    if request.is_xhr:
        a = request.json['a']
        b = request.json['b']
    else:
        a = request.args.get('a')
        b = request.args.get('b')
    my_list = [a, b]
    with open('my_csv.csv', 'wb') as myfile:
        wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
        wr.writerow(my_list)
    return '''
<html>
  <head>
    <title>This is just a testing template!</title>
  </head>
  <body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  </body>
</html>
'''


if __name__ == "__main__":
    app.run(host='0.0.0.0', debug=True)

To test from your Chrome console, you need first to go to http://127.0.0.1:5000/test (after that, jQuery will be available in your browser) then you run the following code:

$.ajax({
    url: "http://127.0.0.1:5000/test",
    method: "POST",
    headers: {'Content-Type':'application/json'},
    data: JSON.stringify({a: 10, b: 25}),
    success: function(data){console.log('result: ' + data);}
});

If you have a Cross-origin issue, add also the below code to your app.py file:

@app.after_request
def after_request(response):
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
    response.headers.add('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, OPTIONS')
    return response
Sign up to request clarification or add additional context in comments.

4 Comments

may I ask you, what if I have a website and a flask app just running as a webserver. The website and the webserver is not related/not on the same domain/IP. Is it possible to fire the flask app from that website then? and how?
Do you mean you have a static website (just with javascript, html, etc) and you want to use it to consume a Flask API?
Yes, but for now, it is not a restful API. Is it possible without turning my app to some kind of restful API? maybe it's off topic.
In this case you need it to be an API, so you will get a structured data (json or xml) and you can play with it in your JavaScript application. If it is not an API, it might return some html templates and this is not very useful.
1

Please refer to http://flask.pocoo.org/docs/0.11/api/#flask.Request

request.args : If you want the parameters in the URL
request.form : If you want the information in the body (as sent by a html POST form)
request.values : If you want both

Try this

@app.route('/test', methods=['GET', 'POST'])
def test():
    my_int1 = request.values.get('a')
    my_int2 = request.values.get('b')

Comments

0

It appears your jQuery reference on that HTML page is not being loaded or not correct, please add this in the <head> here </head> section of your HTML page.

<script src="https://code.jquery.com/jquery-3.1.0.js"></script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.