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 pag
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>
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/
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>