I have been working on creating a JavaScript counter and so far it's working well. However, I recently ran into an issue when trying to use AJAX to retrieve the countdown time. It's strange because it works fine in my original file but not with a PHP file called by AJAX.
This is the link that works perfectly: https://jsfiddle.net/6kvp25vv/
I'm puzzled about what could be causing the problem. Here is the HTML page:
<button onclick="upgrade('meat_max')" id="up_meat_max">+</button>
Clicking the button triggers a function in this JS file which sends a GET request to upgrade.php:
function upgrade(building) {
var file = 'upgrade.php?building=' + building;
ajax(file, function(response) {
document.getElementById('construction').innerHTML += response;
})
}
function ajax(file, fn) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
fn(xmlhttp.responseText);
}
};
xmlhttp.open('GET', file, true);
xmlhttp.send();
}
Below is the code from upgrade.php (the variables sent to this file via AJAX are for testing purposes only):
<div class="time">Time: <span id="timer">?</span></div>
var hour = 2;
var minute = 46;
var second = 45;
// function to create a counter
function clockIt() {
function clockO(digit) {
if(digit<10) {
return '0';
} else {
return '';
}
}
document.getElementById('timer').textContent = hour + ':' + clockO(minute) + minute + ':' + clockO(second) + second;
if(second>0) {
second -= 1;
} else if(minute>0) {
minute -= 1;
second += 59;
} else if(hour>0) {
hour -= 1;
minute += 59;
}
}
// runs the function every second
clockIt();
setInterval(function (){clockIt()}, 1000);