-2

My code in index.php is

<script type="text/javascript">
    window.onload=function(){

        function callback(position) {
           latitude = position.coords.latitude;
           longitude = position.coords.longitude;
             alert(latitude);
             alert(longitude);
        }

        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(callback);
        }

    }
</script>

i need to display the value of latitude and longitude in index.php

<?php echo $lat; ?>, 
<?php echo $long; ?> how can i get value here?
ammv
  • 3
  • 2

1 Answers1

0

First of all, Javascript is client based language and you can not send it to server unless you refresh your page or use AJAX (Asynchronous Javascript And Xml)

AJAX just uses a combination of:

  • A browser built-in XMLHttpRequest object (to request data from a web server)

  • JavaScript and HTML DOM (to display or use the data)*

You can create one controller where you will send your data like this for

function sendData(lat, lon) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      alert("Sent successfuly");
    }
  };
  xhttp.open("GET", "getGeolocation.php?latitude=" + lat + "&longitude=" + lon , true);
  xhttp.send();
}

This way you will pass latitude and longitude by function and then send its values to your controller in getGeolocation.php

You can fetch data like this

$lat = $_GET['lat'];
$lon = $_GET['lon'];
Armin
  • 373
  • 2
  • 13
  • Sorry, I am new to this. I really confused n couldnt get the solution yet. I need this value on loading single-service.php. Can you give me full code. – ammv Jul 28 '18 at 05:27