Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
read geolocation and use jquery ajax to post back
<?php
$name = $_POST["name"];
$lat = $_POST['latitude'];
$lon = $_POST['longitude'];
//TODO: Save to db
echo date('d M Y h:i:s');
?>
<html>
<head>
<title>Tracker by &#936; [PSI]</title>
<style type="text/css">
<!--
input[type=text] { margin-bottom: 8px; display: block; clear: right; width: 150px; }
label { float: left; display: block; width: 50px; text-align: right; padding-right: 8px; }
.buttons { padding-left: 58px; margin-bottom: 8px; }
//-->
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$name = myCookie('name', null);
if ($name) $('#name').val($name);
});
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
$("#latitude").val("not supported.");
$("#longitude").val("not supported.");
}
}
function showPosition(position) {
$("#latitude").val(position.coords.latitude);
$("#longitude").val(position.coords.longitude);
}
function saveLocation()
{
if ($('#name').val() == '')
{
alert('Please enter your name');
$('#name').focus();
return;
}
getLocation();
myCookie('name', $('#name').val());
$.ajax({
url: "data.php",
type: 'POST',
data: $('form').serialize()
}).success(function(response) {
$('#saved').val(response);
}).error(function(response) {
$('#saved').val("an error occurred");
});
}
function myCookie(key, val)
{
if (val != null)
{
document.cookie = key + "=" + val;
return;
}
val = document.cookie;
if (val == null) return false;
return val.replace(key + '=', '').split('; ')[0];
}
</script>
</head>
<body>
<form method="post">
<label for="name">Name:</label>
<input type="text" name="name" id="name" />
<label for="latitude">Lat:</label>
<input type="text" name="latitude" id="latitude" />
<label for="longitude">Long:</label>
<input type="text" name="longitude" id="longitude" />
<div class="buttons">
<input type="button" onclick="javascript:saveLocation();" value="save" />
</div>
<label for="saved">Saved:</label>
<input type="text" name="saved" id="saved" readonly="readonly" />
</form>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment