How can I pass data from Flask to JavaScript in a template?
You can use {{ variable }}
anywhere in your template, not just in the HTML part. So this should work:
<html>
<head>
<script>
var someJavaScriptVar = '{{ geocode[1] }}';
</script>
</head>
<body>
<p>Hello World</p>
<button onclick="alert('Geocode: {{ geocode[0] }} ' + someJavaScriptVar)" />
</body>
</html>
Think of it as a two-stage process: First, Jinja (the template engine Flask uses) generates your text output. This gets sent to the user who executes the JavaScript he sees. If you want your Flask variable to be available in JavaScript as an array, you have to generate an array definition in your output:
<html>
<head>
<script>
var myGeocode = ['{{ geocode[0] }}', '{{ geocode[1] }}'];
</script>
</head>
<body>
<p>Hello World</p>
<button onclick="alert('Geocode: ' + myGeocode[0] + ' ' + myGeocode[1])" />
</body>
</html>
Jinja also offers more advanced constructs from Python, so you can shorten it to:
<html>
<head>
<script>
var myGeocode = [{{ ', '.join(geocode) }}];
</script>
</head>
<body>
<p>Hello World</p>
<button onclick="alert('Geocode: ' + myGeocode[0] + ' ' + myGeocode[1])" />
</body>
</html>
You can also use for
loops, if
statements and many more, see the Jinja2 documentation for more.
Also, have a look at Ford's answer who points out the tojson
filter which is an addition to Jinja2's standard set of filters.
Edit Nov 2018: tojson
is now included in Jinja2's standard set of filters.
Passing variables from Flask to JavaScript
The mobiusklein answers is pretty good, but there is "hack" you should consider. Define your Javascript method to receive params and send data as params to your function.
main.py
@app.route('/')
def hello():
data = {'username': 'Pang', 'site': 'stackoverflow.com'}
return render_template('settings.html', data=data)
app.js
function myFunc(vars) {
return vars
}
settings.html
<html>
<head>
<script type="text/javascript" {{ url_for('static', filename='app.js')}}></script>
<script type="text/javascript">
myVar = myFunc({{data|tojson}})
</script>
</head>
</html>
How to pass data from Flask to Javascript?
Here's a proof of concept app for you:
./app.py
from flask import Flask, jsonify, request, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
@app.route('/calc', methods=['POST'])
def calc_estimation():
text = request.form['text']
results = process_text(text)
return jsonify(results)
def process_text(text: str) -> str:
return [text.upper()] * 10
if __name__ == '__main__':
app.run()
./templates/index.html
<form method="POST" action="/calc" data-calc-form>
<input type="text" name='text'>
<button>Calculate</button>
<pre data-preview></pre>
</form>
<script>
window.addEventListener('DOMContentLoaded', init);
function init() {
const form = document.querySelector('[data-calc-form]');
const textInput = document.querySelector('[name=text]');
const preview = document.querySelector('[data-preview]');
form.addEventListener('submit', async (e) => {
e.preventDefault();
const text = textInput.value;
const results = await fetchEstimations(text);
preview.textContent = JSON.stringify(results, null, 4);
});
}
async function fetchEstimations(text) {
const payload = new FormData();
payload.append('text', text);
const res = await fetch('/calc', {
method: 'post',
body: payload
});
const estimation = await res.json();
return estimation;
}
</script>
When you run the app you get a page like this:
When you enter a text and click calculate you get the result printed into <pre>
How you use the JSON response is up to you, here I just displayed it as is.
Pass variable from Flask HTML Template to JavaScript file for use
Try this. Place the variable inside the slideshow.html within the {% block content %} .. {% endblock %} because it needs to be declared and created first and passed to the base template. Anything outside of the block will likely be ignored by the base template.
{% block content %}
<script> var slideIndex= {{ index }} </script>
...rest of your content
{% endblock %}
not being able to pass a data from flask to html template
The problem is that you are not passing a to the template.
return render_template("base.html", resultat=resultat, a=a)
Also, did you mean result
?
Possible to send data from flask to Javascript?
On the server side you would need to return some kind of data instead of a redirect if the password/username is invalid.
On the Client Side with JavaScript you could post the HTML form as an AJAX call and display the message on the callback.
Anyways I would recommend you to use jQuery for this since its functionality simplifies this quite much. With jQuery a basic AJAX call looks like this:
$('input#loginButton').click( function() {
$.ajax({
url: 'flask-url',
type: 'post',
dataType: 'json',
data: $('form#loginForm').serialize(),
success: function(data) {
// display user dialog
$('#errorDialog').text('Incorrect username/password');
}
});
});
If you want to do this with pure JavaScript you can do something like this:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// do innerHTML changes
document.getElementById('errorDialog').innerHTML = "Incorrect username/password";
}
};
xhttp.open('POST', 'flask-url', true);
xhttp.send();
Where onreadystatechanged means that you got some kind of response by the server
Edit: Since you asked when to use Websockets or AJAX Calls this link should help you.
If you want to implement Websockets with Flask I would recommend you to use flask-socketio which you can simply install via pip.
Feel free to ask if something is still unclear.
passing data from flask to javascript as json not working from separate .js file
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<style>
</style>
</head>
<body>
<div id="graphDiv"></div>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script type="text/javascript">
var graphData = {{ data.chart_data | safe }}
</script>
<script type="text/javascript" src="{{ url_for('static', filename='main.js') }}"></script>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</body>
</html>
Its happening because thats not valid JavaScript syntax. Thats Jinja2 templating syntax.
You need to define graphData
before you can use it in your main.js
file.
Pass data from Flask into a seperate Javascript file
Update: The way I solved this was by simply embedding the javascript into the html, I couldn't find a better way to do this.
Related Topics
Javascript Innerhtml Not Updating Element
Push Objects into an Array in Reactjs
Counting Records in Json Array Using JavaScript and Postman
Rendering Mjpeg Stream in Html5
Count the Number of Times a Same Value Appears in a JavaScript Array
React Js - Uncaught Typeerror: This.Props.Data.Map Is Not a Function
Convert Date String from Yyyymmdd to Dd Mon Yyyy
How to Add Scroll Event in React Component
Prevent Html5 Videos from Downloading the Files on Mobile - Videojs
Angular2: Show Placeholder Image If Img Src Is Not Valid
Passing Data from Blade to Modal in Laravel
Make the Bootstrap Table Scroll-Able Vertically and Horizontally With Fixed Header
Can We Cast a Generic Object to a Custom Object Type in JavaScript
Call External JavaScript Function from React Typescript Components