Passing variables from JS to PHP

mrpeek Posted messages 8 Status Member -  
Reivax962 Posted messages 3742 Status Member -
Bonjour,

I am trying to retrieve JS variables in my PHP code.
Here is my code:

<script type="text/javascript"> function myPosition(position) { var lat = position.coords.latitude; var lon = position.coords.longitude; } if(navigator.geolocation) navigator.geolocation.getCurrentPosition(myPosition); </script>


<?php $latitude = "<script>document.write(lat);</script>" ; echo $latitude; ?>


The PHP part is displaying nothing.
After several tests, I realized that I am able to retrieve the value of a JS variable using this method if it is declared outside of a function.
But here, nothing works, I cannot extract the values 'lat' and 'lon' to display them from the PHP part.
Does anyone have an idea?
Thank you in advance for your help

7 answers

mrpeek Posted messages 8 Status Member 2
 
Hello,

Thank you Jumulka for your response.
However, if I do that, I can indeed call the variable in my PHP code:

 <script type="text/javascript"> var a = 123; </script>


<?php $a = "<script>document.write(a);</script>" ; echo $a; ?>


I think my request is rather: how to retrieve my variables outside of a JS function?

Thank you
2
Reivax962 Posted messages 3742 Status Member 1 011
 
Hello,

I think there is something you haven't quite understood about the interactions between PHP and JavaScript.
It's important to understand that PHP generates source code (JavaScript, HTML, CSS) entirely and then sends the whole page to the client browser, which interprets this code. There are no synchronous exchanges between the two.

At best, we can use JavaScript to make requests to the PHP server (what we call AJAX), but it's asynchronous (that's even the first A of AJAX): you cannot expect PHP to retrieve a variable through this method at the very location of the code that generated the JavaScript that calculated this variable. You will necessarily be in the context of a new request.

The code you present here does not mean that PHP is aware of the value of A. It only knows a string of characters that, on the client side, allows displaying A. This means you cannot use your code to perform operations on the value of A in PHP.
To convince yourself, with the code you wrote, in your browser, do "View Page Source." You will not directly see the value of A written by PHP; you will only see your JavaScript code that tells the browser to display A. PHP never knew the value of A.

Keep in mind that for PHP, JavaScript is just a piece of text that it sends to the client, which can then interpret it.

Xavier
1