The output of this script is fine in browser. I tested on myself and got accurate results. What I want to know is, how do I write the response to a file? I tried writing the response and all I got was the codes written instead of the output.
<?php
$loc = '<body onload="getLocation()">
<p id="demo"></p>
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>';
//File Write
echo $loc;
$log = fopen("loc.txt", "a");
$info = "$loc
";
fwrite($log, $info);
fclose($log);
?>
Output = GPS Coordinates of the browser
You could try something along these lines - untested so there may be errors! I would suggest that you do not echo the body tag as you are like this ...
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['lat'], $_POST['lng'] ) ){
ob_clean();
$bytes = file_put_contents('loc.txt',json_encode( $_POST ) . PHP_EOL, FILE_APPEND );
exit( $bytes ? 'ok' : 'bad foo' );
}
$loc = '<body onload="getLocation()"><p id="demo"></p>
<script>
var x = document.getElementById("demo");
function ajax(url,callback,payload){
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if( this.status==200 && this.readyState==4 )callback.call(this,this.response)
}
xhr.open("POST",url,true);
xhr.send( payload );
}
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition( position ) {
x.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude;
ajax.call( this, location.href, function(r){
alert(r)
}, 'lat='+position.coords.latitude+'&lng=' + position.coords.longitude );
}
</script>';
echo $loc;
?>