I have this piece of JS code:
<script type="text/javascript">
var counter = 0;
function myFunction() {
counter++;
document.getElementById('countervalue').innerHTML = counter;
}
</script>
Which plusses a number with 1 everytime a button is pressed.
The variable "counter" decides what number to start with when the page is loaded. This number is currently 0. But it is supposed to be a number from the database. So I made a database connection using PHP and I now have the database number in a PHP variable. However, how do I implement it on the JS script? I have tried this:
<script type="text/javascript">
var counter = $clicks;
function myFunction() {
counter++;
document.getElementById('countervalue').innerHTML = counter;
}
The variable $clicks is the number from my database that is supposed to be the starting number when clicking the button. I tried this as well, with no luck:
var counter = <?php $clicks ?>;
You're close. You're just forgetting to echo your variable's content:
var counter = <?php $clicks ?>;
should be:
var counter = <?php echo $clicks ?>;
or, if you have short tags enabled:
var counter = <?= $clicks ?>;
var counter = <?=$clicks?>;
Remember the echo
.
var counter = <?php echo $clicks; ?>;
function myFunction() {
counter++;
document.getElementById('countervalue').innerHTML = counter;
}
var counter = <?php echo $clicks; ?>;
Counter value should be assigned as
var counter = <?php echo $clicks ?>;