besmart besmart - 6 months ago 33
JSON Question

AJAX - reload page if JSON has changed

I cannot find a suitable way to achieve this:

I have this script

<script type="text/javascript">
function updateSpots() {

$.ajax({
url : '/epark/api/spots/last',
dataType : 'text',
success : function(data) {

var json = $.parseJSON(data);
var currentMessage = json.dateTime;
var idPosto = json.idPosto;
console.log('current '+currentMessage);
console.log('old '+oldMessage);
if(currentMessage != oldMessage){

setTimeout(function(){location.reload();}, 5000);

$('#idPosto').toggle("higlight");
}
oldMessage = currentMessage;

}
});

}

var intervalId = 0;
intervalId = setInterval(updateSpots, 3000);
var oldMessage ="";

</script>


This should check every 3 seconds if the
dateTime
has changed on the JSON.

The problem is that I cannot get to go further first step. I mean, when the page loads,
oldMessage
empty so the if condition is not satisfied. If I could "jump" this first iteration, then everything would go well...

Answer
var oldMessage = false;

//...

if (oldMessage && oldMessage !== currentMessage) {

//...