You can use Ajax for that:
var httpRequest = null;
function getHttpObject()
{
if (httpRequest != null)
return;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
}
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
else{x.innerHTML="Geolocation is not supported by this browser.";}
}
function showPosition(position)
{
document.getElementById('inputfield3').value = position.coords.latitude;
document.getElementById('inputfield4').value = position.coords.longitude;
getHttpObject();
// I don't know how to get the positions for showPosition, so you may have to change this part.
httpRequest.open("GET", "set_position.php?lat=" + position.coords.latitude + "&lon=" + position.coords.longitude, true);
httpRequest.onreadystatechange = function()
{
if (httpRequest.readyState == 4 && httpRequest.status == 200)
{
// Handle the response here. Show error or success message or whatever...
}
};
httpRequest.send(null);
}
Then on your php script you can set the values to the session, verifying it and verifying the values(of course).
Note: It's been a century I don't write ajax in pure JS. Please warn me for errors.
UPDATE:
I have fixed the way of using the callback of getCurrentPosition
according to this and this documentation.
UPDATE 2:
You can use the common way to send that data to database with a form
. Forget everything above and try this:
Suposing you have a form like this:
<form method="post" action="set_positions.php" id="form1">
<input type="text" id="inputField3" />
<input type="text" id="inputField4" />
</form>
Try this JS code:
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
else{x.innerHTML="Geolocation is not supported by this browser.";}
}
function showPosition(position)
{
document.getElementById('inputfield3').value = position.coords.latitude;
document.getElementById('inputfield4').value = position.coords.longitude;
document.getElementById('form1').submit();
}
So you'll receive those fields in your PHP script. Note that those fields can be hidden
fields too if you doesn't want to user to change its value.