Send users geography to the server every minute

I am trying to write an application that sends a user geolocation to a MYSQL database every minute or so. This is the code that I have now, but it does not work. How do I change this to make it work?

JS:

<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
</head>

<body>
<script>
setInterval ( "onPositionUpdate()", 10000 );
function onPositionUpdate(position)
            {
                var lat = position.coords.latitude;
                var lng = position.coords.longitude;
                jQuery.ajax({ type: "POST", 
                    url:  "myURL/location.php", 
                    data: 'x='+lat+ '&y='+lng , 
                    cache: false, 
                        });
                        }

            if(navigator.geolocation)
               navigator.geolocation.watchPosition(onPositionUpdate);
            else
                alert("navigator.geolocation is not available");



</script>
</body>
</html>

and PHP:

<?php
  include 'config.php';

  // database connection
  $conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);

  // new data

  $x = @$_POST['x'];
  $y = @$_POST['y'];
  // query
  $sql = "update locations set x=?, y=? where username = asd";
  $q = $conn->prepare($sql);
  $q->execute(array($x), ($y));
?>

And I suppose this is the wrong way to send multiple variables, right ?. Firebug console shows me

 missing } after property list
[Break On This Error]   

data: 'x='+lon+'&y='+lat;

When I use only one value, it sends this variable to the server only once and after this console gives:

position is undefined
[Break On This Error]   

var lat = position.coords.latitude;
+3
source share
1 answer

You need to do something like:

var currPosition;
navigator.geolocation.getCurrentPosition(function(position) {
    updatePosition(position);
    setInterval(function(){
        var lat = currPosition.coords.latitude;
        var lng = currPosition.coords.longitude;
        jQuery.ajax({
            type: "POST", 
            url:  "myURL/location.php", 
            data: 'x='+lat+'&y='+lng, 
            cache: false
        });
    }, 1000);
}, errorCallback); 

var watchID = navigator.geolocation.watchPosition(function(position) {
    updatePosition(position);
});

function updatePosition( position ){
    currPosition = position;
}

function errorCallback(error) {
    var msg = "Can't get your location. Error = ";
    if (error.code == 1)
        msg += "PERMISSION_DENIED";
    else if (error.code == 2)
        msg += "POSITION_UNAVAILABLE";
    else if (error.code == 3)
        msg += "TIMEOUT";
    msg += ", msg = "+error.message;

    alert(msg);
}
+4
source

All Articles