Reputation: 3737
I have as an example, two scripts:
home.html
views.py
views.py
has a function in it with various tasks e.g.:
def home()
list1 = [1, 2, 3, 4, 5]
total1 = 0
for x in list1:
total1 += x
list2 = [10, 20, 30, 40, 50]
total2 = 0
for x in list2:
total2 += x
return render_template("home.html")
home.html
has a JavaScript function in it which updates a html/css progressbar depending on what the variable 'value'
is:
<script>
function updateProgressBar(progressBar, value) {
value = Math.round(value);
progressBar.querySelector(".progress__fill").style.width = `${value}%`;
progressBar.querySelector(".progress__text").textContent = `${value}%`;
}
</script>
The python function can vary in completion time. As a way of updating the user of the progress, after every task (i.e. total1
complete, total2
complete) is done in home()
, I want to send a value to the JavaScript function so it can update the progress bar on home.html
e.g. if there were 5 tasks in home()
, it might send the value 20 after task 1, then 40 after task 2 etc.
I am new to 'web development' so struggling to do this and would appreciate any help.
Thank you in advance.
Upvotes: 1
Views: 149
Reputation: 432
One possible solution is to send the data from flask:
# ...
return render_template("home.html", **{
'total1': total1,
'total2': total2
})
Then add two hidden elements in the html you need to use the variables:
<p id="total1" style="display:none;">{{ total1 }}</p>
<p id="total2" style="display:none;">{{ total2 }}</p>
Then use JavaScript to load in those element's data:
const total1 = document.getElementById('total1');
const total2 = document.getElementById('total2');
// ...
Then you are free to use total1 and total2 in your JavaScript file.
A better solution would be if the JavaScript file you have would make an AJAX request towards your flask server, where the server could have a separate function to handle the request and send the data.
Upvotes: 1