Just trying to save the geolocation and IP address to a php file I saws this code, but it doesnt save any info to the pho file
Index.html
<script>
window.onload=function(){
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
}else{
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(pos){
$.post('saver.php',{'lat':pos.coords.latitude,'lng':pos.coords.longitude},function(res){
console.log(res);
});
}
</script>
saver.php
<html>
<script>
<?php
print_r($_POST);
$a = fopen("save.txt", "a");
fwrite($a,"Location: $_POST[lat],$_POST[lng]");
fclose($a);
?>
</script>
</html>
After running the html and clicking allow to get my location. It saves to save.txt, but the result is only.
Location: ,Location: ,
Any idea on what to edit to research. Also would like it to save the IP address as well.
Thank you -Noob
the string needs to be concatenated correctly + $_POST keys need to be wrapped in quotes
and i would suggest adding \n in fwrite so each entry be on a new line
<?php
print_r($_POST);
$a = fopen("save.txt", "a");
fwrite($a,"Location: " . $_POST['lat'] . ",". $_POST['lng'] . "\n");
fclose($a);
?>
and index.html is missing jquery to send the post request. here's the html with jquery file requested from cdn
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
window.onload=function(){
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
}else{
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(pos){
$.post('saver.php',{'lat':pos.coords.latitude,'lng':pos.coords.longitude},function(res){
console.log(res);
});
}
</script>
Side Note: "Geolocation API:This feature is available only in secure contexts (HTTPS), in some or all supporting browsers." MDN Geolocation_API