简体   繁体   中英

Data not passing to php file

Getting trouble sending users geolocation through AJAX into a php file.

Here the code:

                    if (navigator.geolocation) {
                    navigator.geolocation.getCurrentPosition(function(position) {
                            var pos = {
                                lat: position.coords.latitude,
                                lng: position.coords.longitude
                            };

                            infoWindow.setPosition(pos);
                            infoWindow.setContent('You are here');
                            map.setCenter(pos);
                            $.ajax({
                                    type: 'POST',
                                    data: pos,
                                    url: '/template-userslocation.php'
                                    });

                            },
                            function() {
                                handleLocationError(true, infoWindow, map.getCenter());
                            });                     

                   } else {
                           // Browser doesn't support Geolocation
                           handleLocationError(false, infoWindow, map.getCenter());
                   };

Have tried diferent ways to write data like: data: {pos} , data:({pos}) ,
data: {lat: position.coords.latitude, lng: position.coords.longitude},

And that it's the error that I get in template-userslocation.php :

Notice: Undefined index: pos in /home/.../template-userslocation.php on line 7


SOLVED:

The problem was that I've been working in Wordpress and it has it own way to handle with javascript:

here the info

pos is the name of the variable, from PHP it will not know that, it will only see $_POST['lat'] and $_POST['lng']

So use:

$.ajax({
    type: 'POST',
    data: {'pos': pos},
    url: '/wp-content/themes/atripby/template-userslocation.php'
});

Then from PHP access like:

$lat = isset($_POST['pos']['lat']) ? $_POST['pos']['lat'] : null;
$lng = isset($_POST['pos']['lng']) ? $_POST['pos']['lng'] : null;

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