0

I want to store latitude and longitude values in PHP variables, but unable to do so. Here is my code. Can someone help me out here why these values are not getting stored in php variables:

Code:

<!DOCTYPE html>
<html>
<body onload="getLocation()">
<p id="demo"></p>
<script>
var x = document.getElementById("demo");

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}

function showPosition(position) {
    x.innerHTML = "Latitude: " + position.coords.latitude +
    "<br>Longitude: " + position.coords.longitude;
        var lat = position.coords.latitude;
        var longt = position.coords.longitude;
        $.ajax({
      type: 'POST',
      data: { latitude : lat, longitude : longt },
   });

}
        </script>
<?php
        $var = isset($_POST['latitude']);
        $var1 = isset($_POST['longitude']);
        echo $var;
        echo $var1;
?>
</body>
</html>
3
  • You need to understand the difference between client-side code and server-side code. AJAX sends new HTTP requests.
    – SLaks
    Commented Aug 30, 2015 at 20:16
  • so do I need to redirect ajax code to other php page?? Commented Aug 30, 2015 at 20:28
  • Your question makes no sense. What are you trying to do?
    – SLaks
    Commented Aug 30, 2015 at 20:33

2 Answers 2

1

assuming that lat and longt are getting set properly in your javascript (you could do a console.log check to make sure), it looks like you are setting your $var and $var1 variable to the result of the isset() function which returns either true or false, rather than the value of $_POST['latitude'] or $_POST['longitude']. I'm assuming you might have meant:

if (isset($_POST["latitude"])) {
  $var = $_POST['latitude'];
}

if (isset($_POST["longitude"])) {
  $var1 = $_POST['longitude'];
}

Hope that helps.

1
  • I can't edit this code, but the 2nd $var should be $var1, to avoid the 2nd overwriting the first
    – Rob G
    Commented Aug 30, 2015 at 22:28
1

PHP isset() function returns a boolean value. From the documentation, the isset function is used to:

Determine if a variable is set and is not NULL

So in your case you are storing the return value of the function to the variable. It is either true or false.

So here is the corrected code:

if (isset($_POST["latitude"])) {
  $var = $_POST['latitude'];
}

if (isset($_POST["longitude"])) {
  $var1 = $_POST['longitude'];
}

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.