I'm in the learning stages so please bear with me. I've been trying to get answers but often its type="POST" from JS to Flask via AJAX.
This is my app.py.
@app.route("/dashboard", methods=["GET","POST"]);
def dashboard():
yearCount = #Sample list of dict data
return render_template("dashboard.html", yearCount=yearCount)
(edit) How do I get yearCount from above and pass it to a javascript via AJAX? yearCount will be loaded when dashboard.html renders.
This is my js
$.ajax({
url: '/dashboard',
type: "GET",
// data: "How do I get the data yearCount from /dashboard?",
success: function() {
alert(this.url);
}
});
I really appreciate the help! Been tearing my hair out figuratively the whole week trying to look for answers.
Transfer of variables during the rendering process from the template:
You can pass the variable on as json with the jinja filter tojson. If you need the variable outside of your template, you have to pass it as a parameter.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script type="text/javascript">
const yearCount = {{ yearCount | tojson }};
console.log(yearCount);
</script>
</body>
</html>
Loading data while the page is already shown in the browser:
If you want to receive the variable again after the template has been rendered, ajax is the right choice.
from flask import jsonify
@app.route('/count')
def count():
yearCount = # your dict data here.
return jsonify(yearCount)
In your example code you are using the jQuery library. However, implementation with the help of the fetch api is also possible. The following is an example of each.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<!-- Load the jQuery library. -->
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"></script>
<!-- Use the jQuery library to load data with ajax. -->
<script type="text/javascript">
// jQuery ajax
$.ajax({
url: '/count'
}).done((data) => {
console.log(data);
});
</script>
<!-- The fetch api does not require any additional library. -->
<script type="text/javascript">
// fetch api
fetch('/count')
.then(resp => resp.json())
.then(data => console.log(data));
</script>
</body>
</html>