-1

Im trying to create a page where you click on a button, you get your co-ordinates and then the data is saved on a .txt file on the server. This is my code

<!DOCTYPE html>
<html>
<head>
<head>
<body>
<input type="hidden" id="Latitude" name="Lat" value="">
<input type="hidden" id="Longitude" name="Lon" value="">
<button onclick="getLocation()">Get Location</button>
<p id="demo"></p>
<script>
var x = document.getElementById("demo");
var lat,lon;
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    lat=position.coords.latitude;
    lon=position.coords.longitude;
    document.getElementById("Latitude").value = lat;
    document.getElementById("Longitude").value = lon;

    } 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>
<?php
$marker = fopen("markers.txt",a)
$locLat = $_GET['Lat'];
$locLon = $_GET['Lon'];
fwrite($marker,$locLat);
fwrite($marker,$locLon);
?>
</body>
</html>

I can get the user's location, but the PHP code doesn't work. Thanks

  • 1
    fopen("markers.txt",'a'), a should be in brackets – CoreMeltdown Apr 17 '15 at 11:05
  • 5
    You would need to make an ajax call to the server or add form tags and have the user manually submit the form when the values are filled in. Note that the php shown has already run and finished by the time you see the page. – jeroen Apr 17 '15 at 11:05
  • Simply make sure you develop with error reporting on, "a" is clearly a compile error. – Patrick Apr 17 '15 at 11:06
  • Thanks. But is there any way I can have the PHP code run after the Button is pressed or after the Javascript function finishes? – Aaryamann Singh Apr 17 '15 at 14:13

1 Answers1

0

You should correct you code by placing 'a' in double quote and semicolon at the end first line of php code

<?php
$marker = fopen("markers.txt","a");
$locLat = $_GET['Lat'];
$locLon = $_GET['Lon'];
fwrite($marker,$locLat);
fwrite($marker,$locLon);
?>

See this question for how can you include form tag and ajax submit using php here

Community
  • 1
  • 1
Rajnikant Sharma
  • 536
  • 11
  • 27
  • Look at the comments under the OP's question left by others. You have missing quotes around the `a`, plus even when that has been added, the code still won't work. – Funk Forty Niner Apr 17 '15 at 11:30
  • Thanks @fred -ii for pointing out, i have corrected the code. – Rajnikant Sharma Apr 17 '15 at 11:35
  • 1
    You're welcome Rajnikant. But as I stated already; this still won't make the script write the coordinates to file. [Read jeroen's comment as to why...](http://stackoverflow.com/questions/29697386/how-to-write-to-file-from-php#comment47530912_29697386) – Funk Forty Niner Apr 17 '15 at 11:36