-1

I have made/got a code that will get a location with java script. The idea is that it automatically emails someone with the location from the Javascript. However, how would you get the the location in the email, and how would you make it send automatically?

My code is :

<!DOCTYPE html>
<html>
<head>
<title>TestPage</title>
</head>
<body>
<h1>Test</h1>
<p>Your Loaction:
<p id="demo"></p>
<script>
var x = document.getElementById("demo");

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition, showError);
    } else { 
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}

function showPosition(position) {
    x.innerHTML = "Latitude: " + position.coords.latitude + 
    "<br>Longitude: " + position.coords.longitude;
}

function showError(error) {
    switch(error.code) {
        case error.PERMISSION_DENIED:
            x.innerHTML = "User denied the request for Geolocation."
            break;
        case error.POSITION_UNAVAILABLE:
            x.innerHTML = "Location information is unavailable."
            break;
        case error.TIMEOUT:
            x.innerHTML = "The request to get user location timed out."
            break;
        case error.UNKNOWN_ERROR:
            x.innerHTML = "An unknown error occurred."
            break;
    }
}
window.onload = getLocation();
</script>
<?php
$to      = '[email protected]';
$subject = 'Subject';
$message = 'Your location is' <p id="demo">''</p>;

mail($to, $subject, $message,);
?>
</body>
</html>

So i want the php to automatically send and put the Location in the email -- is this even possible? does anyone know how?

Lots of thanks!

3
  • By automatically, you mean when the user visits your page? Commented Apr 28, 2017 at 13:25
  • you mean time interval you send email? Commented Apr 28, 2017 at 13:28
  • you can use ajax and send location then php script send email Commented Apr 28, 2017 at 13:31

1 Answer 1

2

You are mixing PHP and JavaScript.

PHP is executed on the server, THEN the result is sent to the client and renderd, THEN JavaScript is run. Your code is not syntactically correct (because of the <p> tag around the PHP string), but even if it were, it would simply send an e-mail everytime someone requests the webpage, no matter whether they look at it, or whether they have JavaScript or geolocation enabled.

What you want, for whatever reason, is two separate pages - the HTML + JavaScript one which will attempt to get the user's location, and a PHP script. The JavaScript code will need to send an AJAX request to the PHP script with the location, once it obtained it.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.