Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask: Return button's id via ajax

My goal is to return the button's ID to the python script and use it to control stuff the script is doing. After trying a whole evening and basically going through it with try and error I am a little frustrated with it, because there must be something simple I oversaw.

I tried to reduce stuff as much as possible but the button will always return a None inrequest.form.get("button") which leads to an Error 400. As I am not to firm with jQuery I tried a lot there but nothing ever delivered somethign other than a None.

Can anybody help me?

from flask import Flask, render_template_string, request
app = Flask(__name__)

@app.route('/')
def index():
    return render_template_string('''
        <html>
            <head>
                <script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
                <script type="text/javascript">
                    $(document).ready(function() {
                        $('input').on('click', function() {
                            $.ajax({
                                url: "{{ url_for('data_post') }}",
                                method: "POST",
                                data: JSON.stringify($(this).attr("id")),
                                contentType: 'application/json;charset=UTF-8',
                                success: function(data) {
                                    console.log(data);
                                }
                            });
                        });
                    });
                </script>
            </head>
            <body>
                <input type="submit" id="testvalue" name="button" value="button">
            </body>
        </html>
        ''')


@app.route('/data', methods=['GET', 'POST'])
def data_post():
    text = request.form.get("button")
    return text

if __name__ == '__main__':
    app.run(debug=True)
like image 400
ato Avatar asked Jan 22 '26 16:01

ato


1 Answers

Change data_post function to:

@app.route('/data', methods=['GET', 'POST'])
def data_post():
    text = request.data
    return text

and everything should be fine.

like image 177
Vader Avatar answered Jan 25 '26 05:01

Vader



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!