简体   繁体   English

无法从PHP检索AJAX数据

[英]Can't retrieve AJAX data from PHP

I'm trying to create a simple application that finds your location, sends the co-ordintes using AJAX to a PHP file and then calculates distances in the PHP to show nearby shops. 我正在尝试创建一个简单的应用程序,以查找您的位置,使用AJAX将坐标发送到PHP文件,然后计算PHP中的距离以显示附近的商店。

this is my Javascript and ajax: 这是我的Javascript和Ajax:

$(document).ready(function($) {

// Check for GEOLOCATION support 
if (navigator.geolocation) {
window.onload = function() {
var startPos;
var lat;
var lon;
navigator.geolocation.getCurrentPosition(function(position) {
startPos = position;
document.getElementById('currentLat').innerHTML = startPos.coords.latitude;
document.getElementById('currentLon').innerHTML = startPos.coords.longitude;
drawMap(startPos);
}, 

function(error) {
document.getElementById('locationSupport').innerHTML = "Error code: " + error.code;
                            //   0 unknown error
                            //   1 permission denied
                            //   2 position unavailable (error response from locaton provider)
                            //   3 timed out
                        });
                    };
                }
                else {
                    document.getElementById("locationSupport").innerHTML = 'Geolocation is not supported.';
                }
            }); 

function drawMap(position) {
    var myLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
    var lat = position.coords.latitude;
    var lon = position.coords.longitude;
    var mapOptions = {
        zoom: 15,
        center: myLatLng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    var map = new google.maps.Map(document.getElementById('mapCanvas'), mapOptions);
    var userMarker = new google.maps.Marker({position: myLatLng, map: map});
    }       

     var jQT = new $.jQTouch({
                statusBar: 'black-translucent',
                useFastTouch: false, //required for Android
                preloadImages: []
            });

$.ajax({
   type     : "POST",
   url: "http://cs11ke.icsnewmedia.net/DVPrototype/external-data/location.php",
   data : {lat: 'lat', lon: 'lon'},
   dataType : "text",
   success: function(data){
     $("#shopsnotification").html(data);
   }
});   

and then in my PHP I am using: 然后在我的PHP中,我正在使用:

<?php 
    $str_shopresult = '';
    mysqli_select_db($db_server, $db_database);
    $lat = $_POST['lat'];
    $lon = $_POST['lon'];
    $query = "SELECT name, address, 
    (6378.10 * ACOS(COS(RADIANS(latpoint)) * COS(RADIANS(lat)) * COS(RADIANS(longpoint) - RADIANS(lng)) + SIN(RADIANS(latpoint)) * SIN(RADIANS(lat)))) 
    AS distance FROM shops JOIN (SELECT '$lat' AS latpoint, '$lon' AS longpoint) AS p ORDER BY distance LIMIT 10"; 
    $result = mysqli_query($db_server, $query); 
        if (!$result) die("Database access failed: " . mysqli_error($db_server)); 
        while($row = mysqli_fetch_array($result)){ 
    $str_shopresult .= "<strong>" . $row['name']  . "</strong><br>" .
    $row['address'] . "<br><br>"; 
 } 

mysqli_free_result($result); 
echo $str_shopresult; 
mysqli_close($db_server); 
?> 

Can anyone see why this isn't working? 谁能看到为什么这行不通? It just seems to be displaying the shops in a random order rather than using the $lat and $lon variables. 它似乎只是以随机顺序显示商店,而不是使用$ lat和$ lon变量。 Am I retrieving the data wrong? 我检索的数据有误吗? the ajax is displaying the data therefore should be sending the variables correctly (I think) Ajax正在显示数据,因此应该正确发送变量(我认为)

Any help would be greatly appreciated! 任何帮助将不胜感激!

You are sending strings in your data : {lat: 'lat', lon: 'lon'}, but not the values. 您正在data : {lat: 'lat', lon: 'lon'},中发送strings data : {lat: 'lat', lon: 'lon'},但不是值。 You should change this to 您应该将其更改为

data : {lat: lat, lon: lon},

or 要么

data : {"lat": lat, "lon": lon}

Send the values as suggested by KSDaemon and in addition to that, move your $.ajax method to the end of navigator.geolocation.getCurrentPosition success method. 按照KSDaemon的建议发送值,除此之外,将$.ajax方法移动到navigator.geolocation.getCurrentPosition成功方法的末尾。 Otherwise it might get executed before the page is ready and the lat and lon values have been populated. 否则,它可能在页面准备好并且已填充lat和lon值之前执行。

$(document).ready(function ($) {

  // Check for GEOLOCATION support 
  if (navigator.geolocation) {
    window.onload = function () {
      var startPos;
      var lat;
      var lon;
      navigator.geolocation.getCurrentPosition(function (position) {
          startPos = position;
          lat = startPos.coords.latitude;
          lon = startPos.coords.longitude;
          document.getElementById('currentLat').innerHTML = startPos.coords.latitude;
          document.getElementById('currentLon').innerHTML = startPos.coords.longitude;
          drawMap(startPos);

          $.ajax({
            type: "POST",
            url: "http://cs11ke.icsnewmedia.net/DVPrototype/external-data/location.php",
            data: {
              lat: lat,
              lon: lon
            },
            dataType: "text",
            success: function (data) {
              $("#shopsnotification").html(data);
            }
          });
        },

        function (error) {
          document.getElementById('locationSupport').innerHTML = "Error code: " + error.code;
          //   0 unknown error
          //   1 permission denied
          //   2 position unavailable (error response from locaton provider)
          //   3 timed out
        });
    };
  } else {
    document.getElementById("locationSupport").innerHTML = 'Geolocation is not supported.';
  }
});

function drawMap(position) {
  var myLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
  var lat = position.coords.latitude;
  var lon = position.coords.longitude;
  var mapOptions = {
    zoom: 15,
    center: myLatLng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }

  var map = new google.maps.Map(document.getElementById('mapCanvas'), mapOptions);
  var userMarker = new google.maps.Marker({
    position: myLatLng,
    map: map
  });
}

var jQT = new $.jQTouch({
  statusBar: 'black-translucent',
  useFastTouch: false, //required for Android
  preloadImages: []
});

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

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