16

I know how to pass data with a jinja template from python into javascript, but I want to pass a javascript variable into python. I'd like to do it without reloading the page. Is that possible?

blueintegral
  • 1,253
  • 5
  • 20
  • 31

3 Answers3

7

Yes, like monkut said--I believe you want to use JSON and Javascript/jQuery.

This will let allow communication from client to server and back again.

The most applicable example I found was in the Flask snippets/patterns: http://flask.pocoo.org/docs/patterns/jquery/

Allan Anderson
  • 574
  • 4
  • 15
6

I did a similar kind of work in my project and would like to share my code here. I need to find out which post is selected and I was setting the selected post as a global variable at server side, so that I may use it for later comparison. This is how I pass my selected post into Javascript.

<a class="label label-primary"  onclick="myFunction({{very.id}})" > Compare</a>

Now from Javascript to Flask.

function myFunction(x) {
        $.getJSON($SCRIPT_ROOT + '/check_selected', {
        post: x
        }, function(data) {
            var response = data.result;
            console.log(response);
            }
        });
}

This is how I return the result from flask by using JSON.

import json
@main.route('/check_selected', methods=['GET','POST'])
def check_selected():
    global selected
    post = request.args.get('post', 0, type=int)
    return json.dumps({'selected post': str(post)});

As mentioned here, we need to include Google AJAX API in order to load jquery:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="{{
  url_for('static', filename='jquery.js') }}">\x3C/script>')</script>
Waqar Detho
  • 1,502
  • 18
  • 17
-4

Create a JSON string from your view code say, jsonData and in your Jinja Template, write something like

<script type="text/javascript">
    var data = {{ jsonData }};
</script>
abc def foo bar
  • 2,360
  • 6
  • 30
  • 41
  • 4
    The OP specifically mentioned that he already knew how to do this and wanted to go the other direction. – pydsigner Jun 03 '16 at 02:19