How to save javascript variable in php variable??

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Aamit
Forum Newbie
Posts: 1
Joined: Wed Dec 24, 2008 7:11 am

How to save javascript variable in php variable??

Post by Aamit »

Code: Select all

<body onload='window.setInterval("timeHere()", 100)' onunload="sayTime()">
 
</body>
 
here is java script

Code: Select all

 
<script>
var time=1;
 
function timeHere() {
  time = time + 1;
  finalTime = time / 10;
 
}
 
function sayTime() {
  finalTime = time / 10;
  //return finalTime;
  alert("Thank you for coming to my site! \n You have been here " + finalTime + " seconds!");
}
</script>
 
How to save finalTime in php variable like $time??
Reviresco
Forum Contributor
Posts: 172
Joined: Tue Feb 19, 2008 4:18 pm
Location: Milwaukee

Re: How to save javascript variable in php variable??

Post by Reviresco »

Name this document justatest.php:

Code: Select all

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 
<?php
 
if (isset($_POST['hidden_input']) && $_POST['hidden_input'] != "") {
  $time = $_POST['hidden_input'];
  }
?>
 
<script>
var time=1;
 
function timeHere() {
  time = time + 1;
  finalTime = time / 10;
 
}
 
function sayTime() {
  finalTime = time / 10;
  //return finalTime;
  confirm("Thank you for coming to my site! \n You have been here " + finalTime + " seconds!");
  document.test_form.hidden_input.value = finalTime;
  document.test_form.submit();
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>My Time</title>
</head>
 
<body onload='window.setInterval("timeHere()", 100)' onunload="return sayTime()">
 
 <div>
 
 <form name="test_form" action="justatest.php" method="post">
 <input type="hidden" name="hidden_input" value="" />
 </form>
 
 <?php
 
 if(isset($time)) {
   echo '<p>Time: ' . $time . ' seconds.</p>';
   }
 ?>
 
 </div>
 
</body>
</html>
 
Or do with $time what you will -- change the form action to another script running in the background and save to a database, etc.

Also I noticed that the timer keeps going after the confirm popup -- so, you'll have to add a clearInterval() in there somewhere.
Post Reply