NYCPHP Meetup

NYPHP.org

[nycphp-talk] Passing JAVASCRIPT variables to PHP

Rolan Yang rolan at omnistep.com
Sat Apr 5 17:14:01 EDT 2008


I'm see a lot of odd code in the past few posts. $'s mixed in with 
javascript and attempts to blend client side javascript variables with 
server side php variables. Misleading code that simply wont work.
Here's a working example for ya:

<html><head><title>test</title>
<script language="JavaScript" type="text/javascript">
var date = new Date();
var d  = date.getDate();
var day = (d < 10) ? '0' + d : d;
var m = date.getMonth() + 1;
var month = (m < 10) ? '0' + m : m;
var yy = date.getYear();
var year = (yy < 1000) ? yy + 1900 : yy;
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
if (minutes < 10) minutes = "0" + minutes;
if (seconds < 10) seconds = "0" + seconds;
var Datum = (year + "-" + month + "-" + day +' 
'+hours+':'+minutes+':'+seconds);
/* The below line submits the datetime as a GET request upon page load */
new Image().src = '/datetest.php?imgdate='+encodeURI(Datum);
</script>
</head>
<body>
clientdate=<?=$_REQUEST['clientdate']?><br>
<form method="post" action="" name="myform">
<!-- The line below sends the datetime upon form submit -->
<input type="hidden" name="clientdate" value="">
<input type="submit" onClick="document.myform.clientdate.value=Datum;">
</form>
</body>
</html>

The example sends the client date back to the server in 2 different ways.
The first is the img src method, which sends the data immediately after 
the page loads
the second is via the form in the hidden field.

~Rolan



More information about the talk mailing list