My question is: using AJAX, how do I pass a variable in Javascript to my PHP code?
I know PHP is server-side and Javascript is client side and I've read at least a dozen questions asking almost or pretty much the same thing but with each one I seem to be missing something because none of them work. In essence, I am using geolocation to get the user's latitude and longitude on page load and for testing purposes it displays it on the page in respective divs. This part works fine. My issue comes when I try to submit the data to my PHP variables it doesn't connect or something goes wrong, or maybe my code is completely incorrect on this part.
Here is my page for testing in its entirety "test.php":
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
x = navigator.geolocation;
x.getCurrentPosition(success, failure);
function success(position) {
var mylat = position.coords.latitude;
var mylng = position.coords.longitude;
$('#latit').html(mylat);
$('#longit').html(mylng);
}
function failure() {
$('#latit').html("<p>It didn't work</p>")
}
//sends javascript 'mylat' and 'mylng' from above to php script//
$.post("test.php", { lat: mylat , lng : mylng});
</script>
</head>
<body>
<!--only to validate that geolocation function works-->
<div id="latit"></div>
<div id="longit"></div>
<div id="splash">
<h2>Click the button</h2>
<form action="test.php" method="post">
<input type="submit" name="submit" value="Do the thing!" />
</form>
</div>
<?php
//used to validate passing of coordinates
if (isset($_POST['lat'])) {
echo $lat = $_POST['lat'];
}
if (isset($_POST['lng'])) {
echo $lng = $_POST['lng'];
}
?>
</body>
</html>
I am attempting to pass the JS 'mylat' and 'mylng' into PHP's $lat and $lng respectively. Any help would be sincerely appreciated and I apologize for the duplicate question, I'm not sure of a better way to frame what I'm asking for.
Additionally, if there's a way to do this without having to click anything that would be a bonus but I've found nothing for that. I'm very new to web development/programming in general and have almost no experience with Javascript/jQuery/AJAX.
.postto inside the end of your success function. That's a callback function, so if you do the request too soon those values won't be set yet