-4

Here is my code:

<script>
  var g = moment.tz.guess();
</script>

<?php
  $detectTimezone = new DateTimeZone('America/Los_Angeles');
?>

how can I replace America/Los_Angeles with var g?

johnjay22113
  • 133
  • 3
  • 10
  • 10
    You can't. The PHP code executes entirely server-side before the page is even delivered to the client. What are you actually trying to accomplish here? There are *other things* you can do, depending on the actual goal. – David Jun 20 '16 at 13:17
  • You can't do this like that. PHP is processed before Javascript. (Php = server side, javascript = client side) – David Ansermot Jun 20 '16 at 13:17
  • 1
    Possible duplicate of [What is the difference between client-side and server-side programming?](http://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) – Shira Jun 20 '16 at 13:17
  • I dont think you can unless you post it back to the server and get that posted variable from $_POST to set the value – Akshay Khandelwal Jun 20 '16 at 13:17
  • Short answer - you can't. JS lives on the client, PHP on the server. The only way to communicate is via HTTP requests. – Ron Dadon Jun 20 '16 at 13:17
  • @David i'm trying to get the user's timezone which is a javascript variable because i can't do that with PHP. – johnjay22113 Jun 20 '16 at 13:18
  • Possible duplicate of [Embedding JavaScript in PHP](http://stackoverflow.com/questions/29758791/embedding-javascript-in-php) – Adam Konieska Jun 20 '16 at 13:20
  • @johnjay22113: You can get that value client-side and then send it to server-side code, either with a form post (or page load of some kind) or with an AJAX request. Do a Google search for things like "AJAX in PHP example" or similar, there are many examples available. – David Jun 20 '16 at 13:20

2 Answers2

0

Simple answer is You can't.

<?php
    $detectTimezone = new DateTimeZone('America/Los_Angeles');
?>

Above code executes on server side, and JavaScript runs on client side.
The only way to do is using AJAX requests.

Alok Patel
  • 7,842
  • 5
  • 31
  • 47
0

I agree with all the comments saying that normally you cannot, just for the sake of completeness, there are workarounds indeed, like the accepted answer in here: Access a JavaScript variable from PHP.

I would not recommended it however for various reasons, most importantly because it makes things unclear and unnecessary complicated. As others said, it would help to state first what you are aiming to achieve?

Community
  • 1
  • 1
DimP
  • 216
  • 3
  • 9