Flaskr url_for with javascript variable as parameters is not working to python

Question:

I’m trying to use flask with url_for. The problem is that when I try to launch an alert with the value of the javascript variable everything seems ok, but when I try to launch a alert with the url_for the content of the variable is not printed. What I’m doing wrong? or What is missing in my code?

How can I pass a JavaScript variable into the url_for function?

html code:

<a class="dissable_user_btn" data-user_id="{{user.id}}" href="#" title="Change Status"><i class="fa fa-plug"></i>
</a>

JS Code:

<script type="text/javascript">
    $(document).ready(function(){ 
      $('.dissable_user_btn').click(function( event ) {
          var user_id = $(this).data("user_id")
          alert(user_id) //everything ok
          alert ('{{url_for('.dissable', _id=user_id)}}'); //dont print the valur of user_id
</script>
Asked By: franvergara66

||

Answers:

Short answer: you can’t. Flask & Jinja2 render the template on the server side (e.g. Flask is translating all of the {{ }} stuff before it sends the HTML to the web browser).

For a URL like this where you’re including a variable as part of the path you’d need to build this manually in javascript. If this is an XHR endpoint I’d recommend using GET/POST to transfer the values to the server as a better best practice than constructing the URL this way. This way you can use Jinja:

$(document).ready(function(){
    var baseUrl = "{{ url_for('disable') }}";

    $('.dissable_user_btn').click(function(event) {
        var user_id = $(this).data("user_id");

        // first part = url to send data
        // second part = info to send as query string (url?user=user_id)
        // third parameter = function to handle response from server
        $.getJSON(baseUrl, {user: user_id}, function(response) {
            console.log(response);
        });
    });
});
Answered By: abigperson

I found another solution for this. My problem started when I needed to pass a variable with space.

First I created a function to remove trailing and leading spaces

function strip(str) {
return str.replace(/^s+|s+$/g, '');}

After that, I used the function and encoded the URL

<script type="text/javascript">
 $(document).ready(function(){ 
  $('.dissable_user_btn').click(function( event ) {
      var user_id = $(this).data("user_id")
      alert(user_id) 
      user_id    =  strip(user_id).replace(" ","%20");
      alert ('{{url_for('.dissable', _id='user_id')}}.replace('user_id',user_id); 
</script>

It worked pretty nice for me!

This is how I applied to my problem

<script>
   function strip(str) {
       return str.replace(/^s+|s+$/g, '');}

   $(document).ready(function() {
    $('#exportcountry').click(function() {
      var elemento = document.getElementById("countryexportbtn");
      var country  = strip(elemento.textContent).replace(" ","%20");
      $('#exportevent').load("{{ url_for('get_events',country = 'pais')  }}".replace('pais',country));

    });
   });
</script>
Answered By: Leonardo Hermoso
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.