Valentin M Valentin M - 3 years ago 105
Ajax Question

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.

Answer Source

Nothing shows up.

And that's correct you will never get any thing by browsing inde.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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download