Pass JavaScript variable to Flask url_for

Question:

I have an endpoint that takes a value in the url and produces some content that will be inserted into a div. I want to build the url with url_for using a JavaScript variable. However, $variable1 is passed as a string, rather than the value of variable1. How can I pass the value of a JavaScript variable to url_for?

function myFunction() {
    var variable1 = "someString"
    $('#demo').load(
        "{{ url_for('addshare2', share = '$variable1') }}"
    );
}
Asked By: Lucas Amos

||

Answers:

You can’t evaluate JavaScript in Jinja. You’re trying to generate a url on the server side while Jinja is rendering, but you’re referencing a variable that is only available in the JavaScript running on the client browser.

Building the url on the client side is the most straightforward fix. (I don’t know what your route looks like, so here’s an example.)

$('#demo').load('/url/for/addshare2/' + variable1);

However, this isn’t very useful because you can’t use url_for, so you have to hard-code the urls. This is a good sign that what you want is an AJAX endpoint that you pass parameters to, rather than an endpoint that contains values.

@app.route('/addshare2', methods=['POST'])
def addshare2():
    share = request.json['share']
    ...
    return jsonify(result=...)

Now you can generate the url with url_for, and pass the parameters as form data.

$.post(
    '{{ url_for('addshare2') }}',
    {share: variable1},
    function (data) {
        // do something with data on successful response
    }
);
Answered By: davidism

Sometimes I use the following workaround with a temporary placeholder string:

var variable1 = "someString";
$('#demo').load(
    "{{ url_for('addshare2', share='ADDSHARE2') }}".replace("ADDSHARE2", variable1)
);

It doesn’t feel quite right and I’m still looking for a better solution. But it does the job.

Answered By: Falko

It’s possible to send a variable in Jinja by making a template filter to unquote the text returned by url_for()

add this to your app.py:

from urllib.parse import unquote as urllib_unquote

@app.template_filter('unquote')
def unquote(url):
    safe = app.jinja_env.filters['safe']
    return safe(urllib_unquote(url))

then on template do:

function myFunction() {
    var variable1 = "someString"
    $('#demo').load(
        `{{ url_for('addshare2', share = '${variable1}')|unquote }}`
    );
}

this will do the trick.

More on custom template filters: https://flask.palletsprojects.com/en/2.1.x/templating/#registering-filters

if we want to directly send variable with javascript to url_for we can do it like below:

Link.href = "{{ url_for('addshare2', share = '') }}" + variable1

and you can get it through flask or django by requesting the parameter:

@app.route('/addshare2') 
def addshare2(): 
    share = request.args.get('share', None)
    ...
Answered By: AbuAli
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.