Post javascript variables to php
Post javascript variables to php
我试图从js函数发布变量到我的数据库,我已经尝试了几件事,但它不会传递给php。我怎么解决这个问题?我已经添加了我正在使用的代码。
任何帮助都将非常感谢
<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>
json_encode
返回一个包含JSON的字符串。因此,需要添加单引号。改变这个:
var adresses = <?php echo json_encode($data) ?>;
:
var adresses = '<?php echo json_encode($data) ?>';
相关文章:
- Php variable obj to js
- PHP Vars to JavaScript Laravel 5.2
- FullCalendar backend PHP/JS to symfony 3
- AJAX - Javascript array to php
- Json POST To Curl PHP
- $.post-to-php文件在AmazonEC2中没有'似乎不起作用
- jQuery POST to PHP显示在浏览器中,但不显示在PHP文件中
- Unable to receive something in PHP from XMLHttpRequest's
- PHP to Javascript Array
- Regex - PHP to Javascript
- PHP to JS:打印与 AJAX responseText 兼容的 js 变量(如 PHP echo)
- jQuery JSON Decode ( PHP to Javascript)
- php to javaScript
- PHP to communicate with javascript
- Regex - From PHP to JS
- JSON from PHP to JavaScript
- Generate PHP to Javascript
- HTTP GET to PHP to Javascript
- Changing from PHP to JS
- Adding php to javascript (wordpress)