-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'];
                    ?>
3
  • you cannot without "posting" (= sending back to server via ajax, a form, a link,..) Commented Dec 11, 2018 at 15:57
  • You can't because by the time JavaScript runs, PHP has already run. Learn about the page life cycle. Commented Dec 11, 2018 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. Commented Dec 11, 2018 at 15:58

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.