0

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)

2 Answers 2

2

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>
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer. but still I can not acces the data so How can I acess the data from flask
ERR:</br>werkzeug.routing.BuildError: Could not build url for endpoint 'move_forward'. Did you forget to specify values ['title']?
0

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

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

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.