sineverba sineverba - 5 days ago 5
Ajax Question

Ajax: setInterval function doesn't update html (but it works)

I have several

div
s in code. I need to update the html inside, based on API request.
It works, but html doesn't refresh (i.e. if I get via API a new result, html remain same of first iterate, but in firebug I can read new HTML ready to inject in page).

$('div.show-gpio-state').each(function(i, obj) {
var id_gpio = $(this).data('id-gpio');
getGpioState(id_gpio,$(this));
setInterval(function(){getGpioState(id_gpio,$(this))}, 5000);
});

function getGpioState(id_gpio,box) {

$.ajax(
{ url: api_gpio_url+id_gpio,
cache:false,
success: function (result) {
box.html('');
var state = result;
var final_state = '';
if ( (state==='error') || (state==='') ) {
final_state = '<span class="text-danger"><i class="fa fa-fw fa-2x fa-exclamation-triangle"></i></span>';
} else {
if (state==1) {
final_state = '<p class="h2"><i class="fa fa-fire text-success"></i></p>';
} else {
final_state = '<p class="h2"><i class="fa fa-remove text-grey"></i></p>';
}
}
box.html('');
box.html(final_state);
// here in console I have right final state for right box
console.log(final_state);
console.log(box);

}
});

}

Answer

Change this

setInterval(function(){getGpioState(id_gpio,$(this))}, 5000);
setInterval(function(){getGpioState(id_gpio,$(this))}.bind(this), 5000);

or assign $(this) to variable and pass inside setInterval function

Comments