javascriptphpjqueryajaxw3c-geolocation

Cannot pass JS variable to PHP using AJAX


I am trying to get current location of user.

I have JS script to get current Latitude and Longitude with AJAX to send js variables to index.php.

$(document).ready(function() {
if ("geolocation" in navigator){
    navigator.geolocation.getCurrentPosition(function(position){
            var userLat = position.coords.latitude;
            var userLong = position.coords.longitude;
            console.log(userLong);
            console.log(userLat);

            $.ajax({
              type: 'POST',
              url: 'index.php',
              data: {
              userLat : userLat,
              userLong : userLong
              },
              success: function(data)
                {
                  console.log(data);

                }

            });

    });
}else{
    console.log("Browser doesn't support geolocation!");
}});

Then I am trying to do this in my index.php:

echo $_POST['userLat'];
echo $_POST['userLong'];

Nothing shows up. Thanks in advance.


Solution

  • Nothing shows up.

    And that's correct you will never get any thing by browsing index.php because there is no POST at this time , AJAX is internal and the only way to show a result from index.php is in the page that you send from it an ajax call.

    At this :

    success: function(data)
                {
                  console.log(data);
    
                }
    

    you could control where to show your data that comes from index.php by , for example alert(data) or document.getElementById("someelement").innerHTML=data; and so on.