-4

How to use Javacript Variable in PHP Variable? I want to reuse the variable without posting. My code is below;

<!-- User Location -->
                    <script>
                    window.onload = function() {
                      var startPos;
                      var geoSuccess = function(position) {
                        startPos = position;
                        document.getElementById('startLat').innerHTML = startPos.coords.latitude;
                        document.getElementById('startLon').innerHTML = startPos.coords.longitude;
                      };
                      navigator.geolocation.getCurrentPosition(geoSuccess);
                    };
                    </script>
                    <div id='startLat'></div>
                    <div id='startLon'></div>
                    <?php
                    //Getting address from latitude and longitude
                    $latitude = $_COOKIE['startLat'];
                    $longitude = $_COOKIE['startLon'];
                    ?>
Mikev
  • 2,012
  • 1
  • 15
  • 27
ndlelan
  • 11
  • 1
  • 3
  • you cannot without "posting" (= sending back to server via ajax, a form, a link,..) – Jeff Dec 11 '18 at 15:57
  • You can't because by the time JavaScript runs, PHP has already run. Learn about the page life cycle. – epascarello Dec 11 '18 at 15:58
  • It doesn't work that way. You can place PHP variables in javascript, but not the other way around without using Ajax or some other type of network request. – richbai90 Dec 11 '18 at 15:58

1 Answers1

1

PHP is run server-side, and JavaScript is run client-side. You cannot send information from the client to the server, without posting. You can do an AJAX Call to the PHP Script and have it insert into a database.

Jay Mason
  • 446
  • 3
  • 17