douniuta4783 2015-10-06 12:50
浏览 21

将javascript变量发布到php

I am trying to post variables from a js function into my database, I've tried several things but it wont pass it to php. How can I solve this? I've added the code i'm working with.

Any help will be highly appreciated

<html xmlns="http://www.w3.org/1999/xhtml">
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

<?php
// Opens a connection to a mySQL server
$connection=mysqli_connect ('localhost', 'root','', 'koopwoningen');
if (!$connection) {
  die("Not connected : " . mysqli_error());
}
// Search the rows in the markers table
$query = sprintf("SELECT Adres FROM geocodetest");
$result = mysqli_query($connection, $query);
$data = array();
if (!$result) {
  die("Invalid query: " . mysqli_error());
}

if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
       $data[] = $row["Adres"];

    }
} else {
    echo "0 results";
}
?>

<script type="text/javascript">

var adresses = <?php echo json_encode($data) ?>;
var geocoder = new google.maps.Geocoder();

for(i=0;i<adresses.length;i++){
var address = adresses[i];

geocoder.geocode( { 'address': address}, function(results, status) {

if (status == google.maps.GeocoderStatus.OK) {
    var latitude = results[0].geometry.location.lat();
    var longitude = results[0].geometry.location.lng();

    if (window.XMLHttpRequest) {
                        xmlhttp = new XMLHttpRequest();
                    }

                    xmlhttp.open("POST", "geocode.php?latitude=" + latitude + "&longitude=" + longitude);
                    xmlhttp.send();

    alert(latitude + ", " + longitude);

    } 

}); 
}



</script>
<?php

$lati = isset($_POST['latitude']);
$lngi = isset($_POST['longitude']);

$query = mysqli_query($connection, "INSERT INTO geocodetest (lat, lng) VALUES ($lati, $lngi)") or die(mysql_error());  
?>
</html>
  • 写回答

1条回答 默认 最新

  • dsd30433 2015-10-06 12:58
    关注

    json_encode returns a string containing the JSON. Therefore you need to add single quotes. Change this:

    var adresses = <?php echo json_encode($data) ?>;
    

    To this:

    var adresses = '<?php echo json_encode($data) ?>';
    
    评论

报告相同问题?

悬赏问题

  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题