简体   繁体   中英

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.

It might help to define and return a dataType for the ajax.

add this to your list of ajax options

 dataType: 'json',

Then in index.php encode and echo a json string. Remove the lines

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

replace them with

echo json_encode($_POST);

The console.log(data); in the success function should show an object with two items: 'userlat' and 'userLong' and associated values for each. Or it should if $_POST had those two items.

If you want the browser screen to update you will have to take data and use it to modify the DOM.

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.

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