简体   繁体   English

使用AJAX将javascript变量传递给PHP时的未定义变量

[英]Undefined variable when passing javascript variable to PHP with AJAX

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. 本质上,我有两个文件:一个带有geolocation ,JavaScript和AJAX调用,另一个带有php,用于检查数据库并将正确的结果发送回去。 Everything on its own is working perfectly fine, but when I try to send geolocation coordinates to PHP it returns undefined . 一切都可以正常工作,但是当我尝试将geolocation坐标发送到PHP时,它将返回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: 这是我的geolocation和AJAX代码:

<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: 这是处理这些变量的PHP代码:

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" 我得到的是“地理位置似乎在起作用...未定义未定义”

The Geolocation API is asynchronous, so you have to wait for the result to return Geolocation API是异步的,因此您必须等待结果返回

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 );
    });
}
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. 删除两个变量中的var。 Those two are not visible outside displayPosition. 这两个在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. 当您使用$ .ajax调用时,您使用的是在$(document).raedy()下声明的纬度和经度,但是您从未分配任何内容,因此它们是未定义的。 Hope this solve your issue. 希望这能解决您的问题。

PS You se the values in the alert because you're using ones from position, not from your variables. PS您可以在警报中获取值,因为您是从位置而不是从变量中使用值。

Do not use var inside your displayPosition function. 不要在displayPosition函数内部使用var。 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. 您不想在函数范围内声明新变量,而是想为先前在全局范围中声明的现有变量赋值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM