简体   繁体   中英

How do I retrieve location data from javascript using Ajax $_POST in PHP?

I can't get the following code to work in PHP. I want to retrieve the users location then send it to my php script for further processing on the server. The Php won't retrieve the data.

Edited:

    <!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>


<script>

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
  } else {
  alert('Geolocation is required for this page, but your browser doesn&apos;t support it. Try it with a browser that does, such as Opera 10.60.');
}

function successFunction(position) {
  var lat = position.coords.latitude;
  var long = position.coords.longitude;
  var latlong = {"lat" : lat , "long" : long};
  var latlong_encoded = JSON.stringify(latlong);

  $.ajax({
   url: 'PostTest.php',
   type: 'POST',
   data: {"userLocation" : latlong_encoded},
   success: function(data) {
        alert(latlong_encoded);
   }
});

}

function errorFunction(position) {
  alert('Error!');
}
</script>


</body>
</html>

Here is the php code:

<?php
$lat[]= array('coord'=>json_decode($_POST["userLocation"]));
print_r($lat);
?>

I just get an empty array. Array ( [0] => Array ( [coord] => ) )

Try adding

dataType: "json" //for response
contentType: "application/json; charset=UTF-8" //for request

in ajax request..

My snippet:

    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(showLocation);
    }
    else { 
    alert('Geolocation non supported..');
    }

    function showLocation(position) {
        var lat = position.coords.latitude;
        var long = position.coords.longitude;
        $.ajax({
           //YOUR AJAX REQUEST USING LAT, LONG
        });
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM