Home > front end >  How to send variable data form html to flask
How to send variable data form html to flask

Time:06-05

I want to send variable data form html to flask
This is my html js code.
I can not send that variable data to the flask in that way.

<script>
        var data = "shan";
        window.location.href='{{ url_for( "move_forward" , title=data) }}';
</script>

But when I used below way I can send it

<script>
        window.location.href='{{ url_for( "move_forward" , title="shan") }}';
</script>

But finally I want to assign some value to the variable and I want to send it to the flask.
How can I do it

 @app.route("/move_forward/<title>", methods=['GET', 'POST'])
        def move_forward(title):
             print(title)

CodePudding user response:

Jinja templates (the parts using {{ ... }}) are not JavaScript.

When you call render_template, '{{ url_for( "move_forward" , title="shan") }}' gets replaced with something like '/move_forward/shan' and this is what the client receives.

When you do '{{ url_for( "move_forward" , title=data) }}' Flask/Jinja doesn't know what data is because it doesn't interact with the JavaScript, it's just trying to replace a string.

You could instead use a mixture of JavaScript and Jinja to get it working:

<script>
    var baseUrl = '{{ url_for("move_forward") }}';
    var data = "shan";
    window.location.href = baseUrl   "/"   data;
</script>

CodePudding user response:

Thank you @Henry for your answer and I go trough it and do little modification to do it work.

In HTML js script I modify like bellow

var baseUrl = '{{ url_for("move_forward") }}';
var data = "shan";
window.location.href = baseUrl   "?title="   data;

and Then I modify the Flask code like bellow.

@app.route("/move_forward", methods=['GET', 'POST'])
        def move_forward():
            if request.method == 'GET':
                title = request.args.get('title')

Now it's work perfectly. Thank you

  • Related