I am creating a web page using Django and Ajax. I want to refresh my page every 5 seconds depending on the status of a bootstrap toggle switch.
i.e.
- On – Auto refresh table data every 5 seconds
- Off – Do not refresh
jQuery ajax call:
$(document).ready(function () {
$('#auto_switch').hide();
$('#loading').show();
var broker = '{{ broker }}';
$.ajax({
type: "GET",
cache: true,
url: '{% url 'broker:load_data' %}',
data: {
'broker': broker,
},
data_type: 'html',
success: function (data) {
$('#loading').hide()
$('#auto_switch').show();
$('#stock_holdings').html(data.rendered_table);
}
});
$("#auto_switch").change(function () {
if ($(this).prop("checked") == true) {
setInterval(function () {
$.ajax({
type: "GET",
cache: true,
url: '{% url 'broker:load_data' %}',
data: {
'broker': broker,
},
data_type: 'html',
success: function (data) {
$('#loading').hide()
$('#auto_switch').show();
$('#stock_holdings').html(data.rendered_table);
}
});
}, 5000);
else {
$.ajax({
type: "GET",
cache: true,
url: '{% url 'broker:load_data' %}',
data: {
'broker': broker,
},
data_type: 'html',
success: function (data) {
$('#loading').hide()
$('#auto_switch').show();
$('#stock_holdings').html(data.rendered_table);
}
});
}
});
});
I am expecting that if auto-switch (toggle button is enabled), the function setInterval will trigger and the table data will keep refreshing every 5 seconds and on any change in the toggle switch it will find its status as off and no auto refresh will take place. However currently its not auto-refreshing whether the switch is on or off.
2
Answers
Try to use :
instead of