将JS变量传递给新的PHP文件

时间:2015-11-05 16:42:13

标签: javascript php mysql

我正在使用Google地图自动填充并将地址转换为Latitude&经度。我可以在DIV中显示它,但问题是,当我尝试将此变量传递给PHP以将其存储在数据库中时,它不起作用。我尝试用AJAX传递它并失败了。我也尝试用POST直接将它传递给PHP。我无法将此变量发送到数据库。

以下是代码:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    </head>
    <body>
      <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places"></script>
          <script>


        function initialize() {
              var address = (document.getElementById('pac-input'));
              var autocomplete = new google.maps.places.Autocomplete(address);
              autocomplete.setTypes(['geocode']);
              google.maps.event.addListener(autocomplete, 'place_changed', function() {
                  var place = autocomplete.getPlace();
                  if (!place.geometry) {
                      return;
                  }

              var address = '';
              if (place.address_components) {
                  address = [
                      (place.address_components[0] && place.address_components[0].short_name || ''),
                      (place.address_components[1] && place.address_components[1].short_name || ''),
                      (place.address_components[2] && place.address_components[2].short_name || '')
                      ].join(' ');
              }
              /*********************************************************************/
              /* var address contain your autocomplete address *********************/
              /* place.geometry.location.lat() && place.geometry.location.lat() ****/
              /* will be used for current address latitude and longitude************/
              /*********************************************************************/
        var lat =  document.getElementById('lat').innerHTML = place.geometry.location.lat();
        var lon =  document.getElementById('lon').innerHTML = place.geometry.location.lng();
              });
        }

         google.maps.event.addDomListener(window, 'load', initialize);

          </script>



    <form method = "post">
<input id="pac-input" class="controls" type="text"
        placeholder="Enter a location">
       <div id='lat'></div>
        <div id='lon'></div>
<button type="submit" formaction="validate.php" name="submit" formmethod="post">Oddaj</button>
        </form>
   <script type="text/javascript">
 $(document).ready(function() {

            $(".clickable").click(function() {
                var lat = $(this).attr('lat');
                //alert($(this).attr('id'));
                $.ajax({
                    type: "POST",
                    url: 'validate.php',
                    data: {
                          lat: lat,
                              lon: lon
                         },
                    success: function(data)
                    {
                        alert("success!");
                    }
                });
            });
        });
</script>

这里是负责与数据库交谈的PHP

<?php
header('Content-type: text/html; charset=utf-8');
if (isset($_POST['submit']))
{
         $lat = $_POST['lat'];
            $lon = $_POST['lon'];
}
else
{
    echo "Nisem dobil!";
}


    $con= mysqli_connect("localhost","username","password","database");

// Check connection
if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); }

// escape variables for security
$lat = mysqli_real_escape_string($con, $_POST['lat']);
$lon = mysqli_real_escape_string($con, $_POST['lon']);

$sql="INSERT INTO stranka (lon, lat) VALUES (" . $lon . ", ". $lat . ")";

if (!mysqli_query($con,$sql)) {
    echo "Ta error je tukaj, ker že v 5 vrstici ne dobim variable.";
    exit;
}
else {
    echo "Uspelo je";
}

mysqli_close($con);
?>

有人能指出我的结果吗?

1 个答案:

答案 0 :(得分:0)

您已为按钮添加了2个无效的属性: formaction formmethod

虽然这不是它不起作用的原因。

您的表单不起作用的原因是您没有设置表单本身的实际“操作”(您只将属性添加到按钮,这是无效的)。你的表格应该是:

<form method="post" action="validate.php">
    <input id="pac-input" class="controls" type="text" placeholder="Enter a location">
    <div id='lat'></div>
    <div id='lon'></div>
    <button type="submit" name="submit">Oddaj</button>
</form>

您也不应该以这种方式执行jQuery click事件。

希望这是有道理的。