Search code examples
phpjqueryajaxvariablesgeolocation

sending variables to php via ajax and jquery


i want to request the users geolocation via html5-geolocation and send it to the next page I've been told that i've to use ajax/jquery, so this is my code:

<form action="response.php">
        <button onclick="getLocation()">Start</button>

<script>

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

function successFunction(position) {
   var lat = position.coords.latitude;
   var longi = position.coords.longitude;

    $.ajax({
  type: "POST",
  url: "response.php",
  data: { latitude: lat, longitude: longi }
  }).done(function( msg ) {
  alert( "Data Saved: " + msg );
});
}
</script>
</form>

and now i want to "echo" the latitude and longitude on my response.php page but i have no idea how to do :'( I tried this:

$latitude = $_POST["latitude"]; 
echo $latitude; 

but the page is blank


Solution

  • Try This:

    index.html:

    <html>
    <head></head>
    <body>
        <form action="response.php" method="post">
          <input type="hidden" id="latitude" name="latitude" value="" />
          <input type="hidden" id="longitude" name="longitude" value="" />
          <input type="submit" value="Start" />
        </form>
    </body>
    <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
    <script>
        function getLocation() {
    
             var options = {
                enableHighAccuracy: true,
                timeout: 5000,
                maximumAge: 0
             };
    
            function success(pos) {
               successFunction(pos);
            };
    
            function error(err) {
                console.warn('ERROR(' + err.code + '): ' + err.message);
            };
    
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(success, error,options);
            } else { 
                //x.innerHTML = "Geolocation is not supported by this browser.";
            }
        }
    
        function successFunction(position) {
           var lat = position.coords.latitude;
           var longi = position.coords.longitude;
    
            $('#latitude').val(lat);
            $('#longitude').val(longi);
        }
        getLocation();
    </script>
    </html>
    

    response.php:

    <?php
        $latitude = $_POST["latitude"]; 
        $longitude = $_POST["longitude"]; 
        echo "Latitude:".$latitude."</br>";
        echo "longitude:".$longitude;
    ?>
    

    Just create index.html copy and paste this code and make sure that response.php like this.

    /yourprojectdirectory/index.html
    /yourprojectdirectory/response.php