Reputation: 201
Really hoping somebody can help me with this problem, I seem to have this HTML5/Jquery combination working perfectly except it takes a refresh for it to work!
Basically I am using HTML5 geolocation to store the users lat/long in a session and then do some other stuff with it. What I do with it after isn't a problem, it's actually storing the lat/long that is giving me grief.
The code I am using is below. I have commented where I have figured out the problem is.
Any help appreciated!
<?php
session_start();
$url = $_SERVER["REQUEST_URI"];
?>
<script src="modernizr.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script>
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
}
function showPosition(position)
{
localStorage.lat = position.coords.latitude;
localStorage.lon = position.coords.longitude;
}
$(document).ready(function(){
if (Modernizr.geolocation) {
getLocation();
//If I run getLocation() again here it works first time
//A bit of debugging shows that this is where the lat/long values are being lost
$.get("savetosession.php", {lat: localStorage.lat, lon: localStorage.lon}, function(result){
$.get("dothis.php", {url:<?php echo $url; ?>}, function(result){
$("div").html(result);
});
});
}
});
</script>
<div></div>
Upvotes: 2
Views: 754
Reputation: 5725
The problem is that the $.get
is executed before getLocation()
is done (because Javascript is non-blocking).
You could use a callback like this:
<script>
$(document).ready(function(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
localStorage.lat = position.coords.latitude;
localStorage.lon = position.coords.longitude;
$.get("savetosession.php", {lat: localStorage.lat, lon: localStorage.lon}, function(result){
$.get("dothis.php", {url:<?php echo $url; ?>}, function(result){
$("div").html(result);
});
});
});
} //endif
});
</script>
Upvotes: 1