-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

2
  • You mean input variable, not session variable. Different things. Commented Jun 23, 2016 at 11:43
  • Also, try onclick="countdown(<?=$counter?>)" which is the PHP way to "inject a variable in the resulting HTML". Commented Jun 23, 2016 at 11:45

2 Answers 2

1

Try this it will work

onclick="countdown(<?=$counter?>)"
Sign up to request clarification or add additional context in comments.

Comments

-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?>)">

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.