0

I am trying to build a simple mobile app that checks database and gives user the correct venue based on their location. Essentially, I have two files: one with geolocation, JavaScript and AJAX call, and another one with php that checks the database and sends the correct result back. Everything on its own is working perfectly fine, but when I try to send geolocation coordinates to PHP it returns undefined. Why does it not pick up the coordinates (they pop up in a separate window)? How can I fix it?

Here is my geolocation and AJAX code:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script>
            $( document ).ready(function() {

                var latitude;
                var longitude;

                if (navigator.geolocation) {
                  var timeoutVal = 10 * 1000 * 1000;
                  navigator.geolocation.getCurrentPosition(
                    displayPosition, 
                    displayError,
                    { enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 }
                  );
                }
                else {
                  alert("Geolocation is not supported by this browser");
                }

                function displayPosition(position) {
                    var latitude = position.coords.latitude;
                    var longitude = position.coords.longitude;
                  alert("Latitude: " + position.coords.latitude + ", Longitude: " + position.coords.longitude);
                }


                function displayError(error) {
                  var errors = { 
                    1: 'Permission denied',
                    2: 'Position unavailable',
                    3: 'Request timeout'
                  };
                  alert("Error: " + errors[error.code]);
                }

                var request = $.ajax({
                    url: "http://cs11ks.icsnewmedia.net/mobilemedia/ajax.php?latitude=" + latitude + "&longitude=" + longitude,
                    type: "GET",       
                    dataType: "html"
                });

                request.done(function(msg) {
                    $("#ajax").html(msg);         
                });

                request.fail(function(jqXHR, textStatus) {
                    alert( "Request failed: " + textStatus );
                });
           });
    </script>

And here is the bit of PHP that handles these variables:

if (isset($_GET['latitude']) && isset($_GET['longitude'])) {
                        $latitude = $_GET['latitude'];
                        $longitude = $_GET['longitude'];
                        echo "Geolocation seems to work...";
                        echo $latitude;
                        echo $longitude;
                        //continue here
                    }else{
                           echo "Hello. I am your geolocation and I am not working.";
                    }

What I get is "Geolocation seems to work...undefinedundefined"

3 Answers 3

1

The Geolocation API is asynchronous, so you have to wait for the result to return

function displayPosition(position) {
    var latitude = position.coords.latitude;
    var longitude = position.coords.longitude;

    $.ajax({
         url      : "http://cs11ks.icsnewmedia.net/mobilemedia/ajax.php",
         data     : {latitude : latitude, longitude : longitude},
         type     : "GET",       
         dataType : "html"
    }).done(function(msg) {
         $("#ajax").html(msg);         
    }).fail(function(jqXHR, textStatus) {
         alert( "Request failed: " + textStatus );
    });
}
4
  • Thank you for quick reply! Unfortunately, that did not help - nothing shows up now, so I guess the AJAX call is broken. Commented Jan 12, 2014 at 20:37
  • This should work, and it has to be this way in one form or another, as again, the Geolocation API is async, and you can't use the returned data outside the callback. Does the alert pop up, and are you sure the same-origin policy isn't an issue here ? Commented Jan 12, 2014 at 20:53
  • I just tested it on my phone to make sure it's not the emulator fault. Since the alert("Latitude: " + position.coords.latitude + ", Longitude: " + position.coords.longitude); is not there anymore nothing pops up now. But I'm not getting an error either. Just a blank page. Commented Jan 12, 2014 at 21:07
  • I tried moving my old ajax code (the one from question) into displayPosition function and it doesn't work either. Commented Jan 12, 2014 at 21:39
0
function displayPosition(position) {
                var latitude = position.coords.latitude;
                var longitude = position.coords.longitude;
              alert("Latitude: " + position.coords.latitude + ", Longitude: " + position.coords.longitude);
            }

remove var in both variable. Those two are not visible outside displayPosition. When you use the $.ajax call you're using latitude and longitude declared right under the $(document).raedy() but you never assign nothing to them so they're undefined. Hope this solve your issue.

P.S. You se the values in the alert because you're using ones from position, not from your variables.

6
  • Unfortunately they still show up as undefined. But thank you for your help anyway! Commented Jan 12, 2014 at 21:25
  • mix my solution with @adeneo one. You should fix the issue. So wait for the geolocation api..then make ajax call... Commented Jan 13, 2014 at 9:02
  • This is what I thought as well, it makes sense. But whenever I take these two variables out of displayPosition, it breaks ajax and nothing shows up. When I put ajax inside of this funtion, it stops working as well. I've been moving these two bits around in many different configurations and I always get the same result - a blank page. Commented Jan 13, 2014 at 9:23
  • blank page means something wrong in php file. Try to set ajax method to post and also change$_GET to $_POST. Commented Jan 13, 2014 at 9:27
  • Still, blank page. I don't think it can be case of php because there's more code than what I just posted. Just to double check I swapped it for a txt test file. It doesn't call that either. With ajax outside of displayPosition and these two variables inside of it - ajax works. Whenever I move variables out or put ajax inside of displayPosition - it breaks. Commented Jan 13, 2014 at 9:56
-1

Do not use var inside your displayPosition function. You do not want to declare new variables inside the scope of the function, you want to assign values to the existing variables you declared in the global scope earlier.

2
  • I declared them at the very top. In the displayPosition function I am just assigning the values. Unless there is a different way to do it that might help? Commented Jan 12, 2014 at 20:42
  • See @FuMe answer, basically saying the same thing. If you are "just assigning the values", you should not be using the var keyword. By using var inside the displayPosition function you are creating new variables that only exist inside that function. See here. Have you tried echoing the latitude and longitude variables to console right before the ajax call? That could tell you for sure what they hold when they are being sent to the PHP script. Commented Jan 13, 2014 at 5:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.