[thelist] javascript date into php

Symeon Charalabides symeon at systasis.com
Fri Jun 21 17:55:05 CDT 2013

Hi Bob,

I think you're under the impression that JS is parsed before PHP on a page, and can therefore pass its parsed values into PHP. That is not correct. PHP is parsed first into HTML/JS by the server, the page is then sent to the browser and JS is then evaluated by the browser.

For instance, if I've understood this correctly, you seem to believe that the value of $date in your PHP script is 5/21. That is not the case, though. The value of $date is the string "<script>document.write(month + '/' + day)</script>". You see it as "5/21" when you dump it on the browser because the browser evaluates the JS expression, but PHP doesn't - it's just a string. The same goes for $jmonth, and that is why it all falls down when you try to do arithmetic with those variables.

Since PHP is parsed before JS, you can't really pass JS values into PHP on the same page. Therefore, your options are:

- Use PHP's datetime functions or, if you MUST use JS (presumably because you want the client's datetime),
- Use JS to populate a form field, possibly hidden, with the date(s) you want, then pass them on to PHP as GET/POST variables


>  -------Original Message-------
>  From: Bob Meetin <bobm at dottedi.biz>
>  To: thelist at lists.evolt.org <thelist at lists.evolt.org>
>  Subject: [thelist] javascript date into php
>  Sent: 21 Jun '13 22:18
>  I'm trying to employ javascript to obtain the local date and pull it into php. This partly works:
>  <script>
>  var currentTime = new Date()
>  var month = currentTime.getMonth()
>  var day = currentTime.getDate()
>  <?php $date = "<script>document.write(month + '/' + day)</script>"?>
>  <?php $jmonth = "<script>document.write(month)</script>"?>
>  </script>
>  <?php
>  echo "JavaScript Local Date: $date<br>";
>  $jmonth = chop($jmonth);
>  // $jmonth = (int)$jmonth; // fails
>  echo "jmonth: $jmonth<br>";
>  $pmonth = intval($jmonth); // no difference
>  $pmonth = $pmonth + 1;
>  echo "pmonth: $pmonth<br>";
>  if ( $pmonth > 5 ) { echo "Success"; } else { echo "Fail"; }
>   >
>  The javascript seems to be working and $jmonth reads the javascript value fine. However, once I get into PHP and attempt to do some simple math with the $jmonth/$pmonth value it falls apart. The php month gets interpreted as 0.
>  What am I missing?
>  --
>  * * Please support the community that supports you.  * *
>  http://evolt.org/help_support_evolt/
>  For unsubscribe and other options, including the Tip Harvester
>  and archives of thelist go to: http://lists.evolt.org
>  Workers of the Web, evolt !

Symeon Charalabides (cosmopolite trainee)

More information about the thelist mailing list