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:
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.)
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.Now you can generate the url with
url_for
, and pass the parameters as form data.