Reputation: 51
I want a countdown on my website that starts with a value from php (out of a MySQL database).
Currently I use the following function:
<script type="text/javascript">
var seconds;
var temp;
var tijd = <? echo json_encode($t); ?>
function countdown() {
seconds = document.getElementById('countdown').innerHTML;
seconds = parseInt(seconds, tijd);
if (seconds == 1) {
temp = document.getElementById('countdown');
temp.innerHTML = "0";
return;
}
seconds--;
temp = document.getElementById('countdown');
temp.innerHTML = seconds;
timeoutMyOswego = setTimeout(countdown, 1000);
}
countdown();
</script>
But in case $t is not 10 the value is increasing with strange steps. How can I solve this? I don't have experience with javascript, so that's the problem.
Besides that, when I adding this script, the following code:
header('Content-Type: text/html; charset=iso-8859-1');
isn't working anymore, because for example " ë " is represented with a ? in the text. I don't know why this is happening?
Who can helps me? Thanks in advance.
Upvotes: 0
Views: 213
Reputation: 82
If you want a human-readable counter you must use 10 in the second parameters of parseInt function
"Specify 10 for the decimal numeral system commonly used by humans."
Then the only number you want to retrieve from database is the start of the counter.
I think you have some like this in your HTML code:
<div id="countdown"><?php echo $startCounterFromDB; //This is the start of the counter ?></div>
And in you want to keep your code, in your JavaScript you only have to change the second parameter of the parseInt function.
<script type="text/javascript">
var seconds;
var temp;
var tijd = 10; //always use 10
function countdown() {
seconds = document.getElementById('countdown').innerHTML;
seconds = parseInt(seconds, tijd);
if (seconds == 1) {
temp = document.getElementById('countdown');
temp.innerHTML = "0";
return;
}
seconds--;
temp = document.getElementById('countdown');
temp.innerHTML = seconds;
timeoutMyOswego = setTimeout(countdown, 1000);
}
countdown();
</script>
Finally UTF-8 is a PSR standard for all files, but you don't need to use json_encode function, because you only need to print a single number.
This code will work.
Upvotes: 1