Search code examples
javascriptphpjquerycountdowncountdowntimer

Trying to use PHP variable in Javascript


I am trying to bring a php variable into my javascript code to use for a countdown timer. Because of the other functions happening based on the timestamp php variable, I need to to be in php as well.

<?php  $access = '1443907640'; ?>
<script>
    $(function() {
        var access = <?php echo $access ?>;
        var note = $('.note'),

        ts = (new Date(access * 1000)).getTime() + 1 * 24 * 60 * 60 * 1000;


        $('.countdown').countdown({
        timestamp: ts,
        callback: function(days, hours, minutes, seconds) {

            var message = "";

            message += days + "<small class='opacity'>D</small>, ";
            message += hours + "<small class='opacity'>H</small>, ";
            message += minutes + "<small class='opacity'>M</small>, ";
            message += seconds + "<small class='opacity'>S</small>";

            note.html(message);

        }


        });
    });
</script>   

Then I call call it with html here but doesn't work

<div class="note"></div>

Solution

  • I think the real problem in your code is in the end of this line :

    var note = $('.note'),
    

    Replace , by ; and it should work.

    NOTE : line var access = <?php echo $access ?>; work fine in my test.


    To solve the following error :

    TypeError: $(...).countdown is not a function
    

    You should add jquery.countdown script :

     <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.countdown/2.1.0/jquery.countdown.js"></script>
    

    Hope this helps.