Passing data from javascript into Flask

33,981

Solution 1

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/

Solution 2

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>
Share:
33,981
blueintegral
Author by

blueintegral

Computer Engineering Student at Georgia Tech

Updated on June 22, 2020

Comments

  • blueintegral
    blueintegral almost 4 years

    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?

  • pydsigner
    pydsigner almost 8 years
    The OP specifically mentioned that he already knew how to do this and wanted to go the other direction.
  • Ciasto piekarz
    Ciasto piekarz almost 7 years
    how would you call function on page load instead of user click button and then pass data from javascript to flask