Pass JavaScript variable to Flask url_for
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') }}"
);
}
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.
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
}
);