0

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 ?>;
1
  • var counter = <?php echo $clicks ?>; should do Commented Apr 26, 2013 at 12:58

5 Answers 5

8

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 ?>;
Sign up to request clarification or add additional context in comments.

Comments

5
var counter = <?=$clicks?>;

Comments

4

Remember the echo.

var counter = <?php echo $clicks; ?>;
function myFunction() {
    counter++;
    document.getElementById('countervalue').innerHTML = counter;
}

Comments

0

var counter = <?php echo $clicks; ?>;

Comments

0

Counter value should be assigned as

var counter = <?php echo $clicks ?>;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.