-1

I am wondering if there's a way to pass a session variable (or any variable initiated in the PHP code) as an argument in a JavaScript function. As for now the code below wouldn't work. However, I am unaware of what the issue might be.

Here's the JavaScript code

var counter = setInterval(countdown, 1000);

function countdown(var seconds) {
 seconds = seconds - 1;
 if (seconds <= 0) {
  clearInterval(counter);
  document.getElementById("countdown").innerHTML = null;
  return;
 }
 
 
 document.getElementById("countdown").innerHTML = seconds + " seconds left";
 return seconds;
}

Here's the HTML code

<?php
if(isset($_POST['btn-submit']) {
   $counter = 30;
}
?>

<html>
      <body>
  <div id="container">
   <form method="post">
    <button type="submit" name="btn-submit" onclick="countdown($counter)">Confirm</button>
   </form>
   <p id="countdown"></p>
  </div>
 </body>
</html>

Thanks in advance!

EDIT: One of the issues was putting 'var' in front of 'seconds' in the function

user3510657
  • 77
  • 1
  • 8

2 Answers2

1

Try this it will work

onclick="countdown(<?=$counter?>)"
M.Tanzil
  • 1,987
  • 1
  • 12
  • 28
-1

You can use the php $counter variable on the client side if you echo it out and assign it to a javascript variable.

<?php
if(isset($_POST['btn-submit']) {
   $counter = 30;
}
?>

<html>
    <head>
        <script>
           var counter = <?php echo $counter; ?>;
        </script>
    </head>
    <body>
        <div id="container">
            <form method="post">
                    <button type="submit" name="btn-submit" onclick="countdown(counter)">Confirm</button>
            </form>
            <p id="countdown"></p>
            </div>
    </body>
</html>

Or inject it directly into the HTML-code:

<button type="submit" name="btn-submit" onclick="countdown(<?php=$counter?>)">
eol
  • 23,236
  • 5
  • 46
  • 64