0👍
✅
Here’s one solution: Building on @MichaelCacciano’s suggestion, I wrapped the JQuery in a function (refresh_graph
), and also dropped the Django placeholder in favour of a tag (currentPrice
), both of which now update every second, as follows:
<script>
function refresh_graph() {
{% block jquery %}
var endpoint = "{% url 'chart_data' market.id %}"
var defaultData = []
var labels = []
$.ajax({
method: "GET",
url: endpoint,
success: function(data){
defaultData = data.prices
price_array_length = defaultData.length + 1
labels = data.price_dates
var current = defaultData[defaultData.length-1];
document.getElementById('currentPrice').innerHTML = current;
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets : [{
label: 'Market price',
data: defaultData,
backgroundColor: [
'rgba(54, 162, 235, 0.2)',
],
borderColor: [
'rgba(54, 162, 235, 1)',
],
borderWidth: 2
}]
},
options: {
scales: {
yAxes: [{
ticks: {
suggestedMin: 0,
suggestedMax: 1
}
}]
},
animation: {
duration: 0 // general animation time
},
hover: {
animationDuration: 0 // duration of animations when hovering an item
},
responsiveAnimationDuration: 500 // animation duration after a resize
}
})
}
})
setTimeout(refresh_graph, 1000);
}
setTimeout(refresh_graph, 0);
{% endblock %}
</script>
Source:stackexchange.com