使用AJAX将JavaScript变量从JavaScript传递到PHP

使用AJAX将JavaScript变量从JavaScript传递到PHP,php,jquery,ajax,Php,Jquery,Ajax,我的PHP文件有一些问题。所以基本上我正在做一个项目,从用户那里获取两个地址,然后它使用javascript显示他们的路线,一旦他们单击submit,我想把这两个变量传递给PHP文件。我做了很多研究,发现我需要AJAX调用。我遇到的问题是AJAX调用工作得很好,但当我转到PHP文件时,它会给我一个错误,即没有定义变量。有人,请给我解释一下我做错了什么 JavaScript代码: /* =======================================================

我的PHP文件有一些问题。所以基本上我正在做一个项目,从用户那里获取两个地址,然后它使用javascript显示他们的路线,一旦他们单击submit,我想把这两个变量传递给PHP文件。我做了很多研究,发现我需要AJAX调用。我遇到的问题是AJAX调用工作得很好,但当我转到PHP文件时,它会给我一个错误,即没有定义变量。有人,请给我解释一下我做错了什么

JavaScript代码:

 /* ============================================================================================
   Reference: https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-directions
   ==============================================================================================
  */ 
  function initMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
      mapTypeControl: false,
      center: {lat: 41.881832, lng: -87.623177},
      zoom: 13
    });

    new AutocompleteDirectionsHandler(map);
  }

   /**
    * @constructor
   */
  function AutocompleteDirectionsHandler(map) {
    this.map = map;
    this.originPlaceId = null;
    this.destinationPlaceId = null;
    this.travelMode = 'DRIVING';
    var originInput = document.getElementById('origin-input');
    var destinationInput = document.getElementById('destination-input');
    var submit_button = document.getElementById('button-to-submit');
    /*var modeSelector = document.getElementById('mode-selector');*/
    this.directionsService = new google.maps.DirectionsService;
    this.directionsDisplay = new google.maps.DirectionsRenderer;
    this.directionsDisplay.setMap(map);

    var originAutocomplete = new google.maps.places.Autocomplete(
        originInput, {placeIdOnly: true});
           var destinationAutocomplete = new google.maps.places.Autocomplete(
        destinationInput, {placeIdOnly: true});

    /*this.setupClickListener('changemode-walking', 'WALKING');
    this.setupClickListener('changemode-transit', 'TRANSIT');
    this.setupClickListener('changemode-driving', 'DRIVING');*/

    this.setupPlaceChangedListener(originAutocomplete, 'ORIG');
    this.setupPlaceChangedListener(destinationAutocomplete, 'DEST');

    this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(originInput);
    this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(destinationInput);
    this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(submit_button);
    /*this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(modeSelector);*/
  }

  // Sets a listener on a radio button to change the filter type on Places
  // Autocomplete.
  /* AutocompleteDirectionsHandler.prototype.setupClickListener = function(id, mode) {
    var radioButton = document.getElementById(id);
    var me = this;
    radioButton.addEventListener('click', function() {
      me.travelMode = mode;
      me.route();
    });
  }; */

  AutocompleteDirectionsHandler.prototype.setupPlaceChangedListener = function(autocomplete, mode) {
    var me = this;
    autocomplete.bindTo('bounds', this.map);
    autocomplete.addListener('place_changed', function() {
        var place = autocomplete.getPlace();
      if (!place.place_id) {
        window.alert("Please select an option from the dropdown list.");
        return;
      }
      if (mode === 'ORIG') {
        me.originPlaceId = place.place_id;
      } else {
        me.destinationPlaceId = place.place_id;
      }
      me.route();
    });

  }; 

  AutocompleteDirectionsHandler.prototype.route = function() {
    if (!this.originPlaceId || !this.destinationPlaceId) {
      return;
    }
    var me = this;

    this.directionsService.route({
      origin: {'placeId': this.originPlaceId},
      destination: {'placeId': this.destinationPlaceId},
      travelMode: this.travelMode
    }, function(response, status) {
      if (status === 'OK') {
        me.directionsDisplay.setDirections(response);
        origin_addr = document.getElementById('origin-input').value;
        //console.log(origin_addr);
        destination_addr = document.getElementById('destination-input').value;
        //console.log(destination_addr);
        //var place_id = document.getElementById('origin-input');
      } else {
        window.alert('Directions request failed due to ' + status);
      }
     });

  };

  $("#button-to-submit").click(function() {
   $.ajax({
         url: "Database/save-points.php",
         type: "POST", //send it through get method
         data: { 
          origin_address: origin_addr,
          destination_address: destination_addr
          },
          success: function(response) {
        //Do Something
           console.log("Succeed");
           location.href="Database/save-points.php";
          },
          error: function(xhr) {
    //Do Something to handle error
          }
        });  
});
PHP代码:

<?php
    $origin_address = $_POST['origin_address'];
    $destination_address = $_POST['destination_address'];
    echo $origin_address;
    echo $destination_address;
?>

我有一个将JS变量传递给PHP的示例

JS(
url
content
是JS变量):

dynamic.php
中:

    <?php

        $vars = serialize($_POST); /*easier access*/

        $file_path = "../".$vars["filepath"];
        $file_content = $var["filecontent"]; /*example of assigning a JS var's value to a PHP var*/
        $fh = fopen($file_path, 'w+') or die("could not open file");
        fwrite($fh, $file_content."\n");
        fclose($fh);

    ?>

我有一个将JS变量传递给PHP的示例

JS(
url
content
是JS变量):

dynamic.php
中:

    <?php

        $vars = serialize($_POST); /*easier access*/

        $file_path = "../".$vars["filepath"];
        $file_content = $var["filecontent"]; /*example of assigning a JS var's value to a PHP var*/
        $fh = fopen($file_path, 'w+') or die("could not open file");
        fwrite($fh, $file_content."\n");
        fclose($fh);

    ?>
/*maps.php*/

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr" dir="ltr">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.js" type="text/javascript"></script>
<style>
  /* Always set the map height explicitly to define the size of the div
   * element that contains the map. */
  #map {
    height: 100%;
  }
  /* Optional: Makes the sample page fill the window. */
  html, body {
    height: 100%;
    margin: 0;
    padding: 0;
  }
  .controls {
    margin-top: 10px;
    border: 1px solid transparent;
    border-radius: 2px 0 0 2px;
    box-sizing: border-box;
    -moz-box-sizing: border-box;
    height: 32px;
    outline: none;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
  }

  #origin-input,
  #destination-input {
    background-color: #fff;
    font-family: Roboto;
    font-size: 15px;
    font-weight: 300;
    margin-left: 12px;
    padding: 0 11px 0 13px;
    text-overflow: ellipsis;
    width: 200px;
  }

  #origin-input:focus,
  #destination-input:focus {
    border-color: #4d90fe;
  }

  #mode-selector {
    color: #fff;
    background-color: #4d90fe;
    margin-left: 12px;
    padding: 5px 11px 0px 11px;
  }

  #mode-selector label {
    font-family: Roboto;
    font-size: 13px;
    font-weight: 300;
  }

</style>
</head>
<body>
<input id="origin-input" class="controls" type="text"
    placeholder="Enter an origin location">

<input id="destination-input" class="controls" type="text"
    placeholder="Enter a destination location">

<div id="mode-selector" class="controls">
  <input type="radio" name="type" id="changemode-walking" checked="checked">
  <label for="changemode-walking">Walking</label>

  <input type="radio" name="type" id="changemode-transit">
  <label for="changemode-transit">Transit</label>

  <input type="radio" name="type" id="changemode-driving">
  <label for="changemode-driving">Driving</label>

  <input type="submit" id="button-to-submit" value="SAVE !" />
</div>

<div id="map"></div>
 <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOU_KEY&libraries=places"></script>
<script type="text/javascript">
  // This example requires the Places library. Include the libraries=places
  // parameter when you first load the API. For example:

  function initMap() {
    var map = new google.maps.Map(document.getElementById('map'), {
      mapTypeControl: false,
      center: {lat: -33.8688, lng: 151.2195},
      zoom: 13
    });

    new AutocompleteDirectionsHandler(map);
  }

   /**
    * @constructor
   */
  function AutocompleteDirectionsHandler(map) {
    this.map = map;
    this.originPlaceId = null;
    this.destinationPlaceId = null;
    this.travelMode = 'WALKING';
    var originInput = document.getElementById('origin-input');
    var destinationInput = document.getElementById('destination-input');
    var modeSelector = document.getElementById('mode-selector');
    this.directionsService = new google.maps.DirectionsService;
    this.directionsDisplay = new google.maps.DirectionsRenderer;
    this.directionsDisplay.setMap(map);

    var originAutocomplete = new google.maps.places.Autocomplete(
        originInput, {placeIdOnly: true});
    var destinationAutocomplete = new google.maps.places.Autocomplete(
        destinationInput, {placeIdOnly: true});

    this.setupClickListener('changemode-walking', 'WALKING');
    this.setupClickListener('changemode-transit', 'TRANSIT');
    this.setupClickListener('changemode-driving', 'DRIVING');

    this.setupPlaceChangedListener(originAutocomplete, 'ORIG');
    this.setupPlaceChangedListener(destinationAutocomplete, 'DEST');

    this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(originInput);
    this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(destinationInput);
    this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(modeSelector);
  }

  // Sets a listener on a radio button to change the filter type on Places
  // Autocomplete.
  AutocompleteDirectionsHandler.prototype.setupClickListener = function(id, mode) {
    var radioButton = document.getElementById(id);
    var me = this;
    radioButton.addEventListener('click', function() {
      me.travelMode = mode;
      me.route();
    });
  };

  AutocompleteDirectionsHandler.prototype.setupPlaceChangedListener = function(autocomplete, mode) {
    var me = this;
    autocomplete.bindTo('bounds', this.map);
    autocomplete.addListener('place_changed', function() {
      var place = autocomplete.getPlace();
      if (!place.place_id) {
        window.alert("Please select an option from the dropdown list.");
        return;
      }
      if (mode === 'ORIG') {
        me.originPlaceId = place.place_id;
      } else {
        me.destinationPlaceId = place.place_id;
      }
      me.route();
    });

  };

  AutocompleteDirectionsHandler.prototype.route = function() {
    if (!this.originPlaceId || !this.destinationPlaceId) {
      return;
    }
    var me = this;

    this.directionsService.route({
      origin: {'placeId': this.originPlaceId},
      destination: {'placeId': this.destinationPlaceId},
      travelMode: this.travelMode
    }, function(response, status) {
      if (status === 'OK') {
        me.directionsDisplay.setDirections(response);
      } else {
        window.alert('Directions request failed due to ' + status);
      }
    });
  };

/************************************/
$(document).ready( function() {
$("#button-to-submit").click(function() {

origin_addr = $("#origin-input").val();
destination_addr = $("#destination-input").val();

        $.ajax({
        type: "POST",
        url: "maps.exe.php",
        data: {
        origin_address: origin_addr,
        destination_address: destination_addr
        },
        success: function(response){
        alert(response);
        window.location.href = 'test-resp.php?'+response;
        }
        });
        return false;
        });
});
</script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&libraries=places&callback=initMap" async defer></script>
</body>
</html>

/*始终明确设置贴图高度以定义div的大小
*包含映射的元素*/
#地图{
身高:100%;
}
/*可选:使示例页面填充窗口*/
html,正文{
身高:100%;
保证金:0;
填充:0;
}
.控制{
边缘顶部:10px;
边框:1px实心透明;
边界半径:2px 0 0 2px;
框大小:边框框;
-moz框大小:边框框;
高度:32px;
大纲:无;
盒影:0 2px 6px rgba(0,0,0,0.3);
}
#原点输入,
#目的地输入{
背景色:#fff;
字体系列:Roboto;
字体大小:15px;
字体大小:300;
左边距:12px;
填充:0 11px 0 13px;
文本溢出:省略号;
宽度:200px;
}
#原点输入:焦点,
#目的地输入:焦点{
边框颜色:#4d90fe;
}
#模式选择器{
颜色:#fff;
背景色:#4d90fe;
左边距:12px;
填充:5px11px 0px 11px;
}
#模式选择器标签{
字体系列:Roboto;
字体大小:13px;
字体大小:300;
}
行走
换乘
驱动
//此示例需要Places库。包括图书馆=地方
//第一次加载API时的参数。例如:
函数initMap(){
var map=new google.maps.map(document.getElementById('map'){
mapTypeControl:false,
中心:{lat:-33.8688,lng:151.2195},
缩放:13
});
新的自动完成方向Shandler(map);
}
/**
*@constructor
*/
函数自动完成方向Shandler(map){
this.map=map;
this.originPlaceId=null;
this.destinationPlaceId=null;
this.travelMode='WALKING';
var originInput=document.getElementById('origin-input');
var destinationInput=document.getElementById('destination-input');
var modeSelector=document.getElementById('mode-selector');
this.directionsService=新的google.maps.directionsService;
this.directionsDisplay=新的google.maps.DirectionsRenderer;
此.directionsDisplay.setMap(map);
var originAutocomplete=new google.maps.places.Autocomplete(
原始输入,{placeIdOnly:true});
var destinationAutocomplete=new google.maps.places.Autocomplete(
destinationInput,{placeIdOnly:true});
这个.setupClickListener('changemode-walking','walking');
这个.setupClickListener('changemode-transit','transit');
此.setupClickListener('changemode-driving','driving');
此.setupPlaceChangedListener(originAutocomplete,'ORIG');
此.setupPlaceChangedListener(destinationAutocomplete,'DEST');
this.map.controls[google.maps.ControlPosition.TOP\u LEFT].push(原始输入);
this.map.controls[google.maps.ControlPosition.TOP\u LEFT].push(destinationInput);
this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(模式选择器);
}
//在单选按钮上设置侦听器以更改位置上的筛选器类型
//自动完成。
AutoCompletedDirectionShandler.prototype.setupClickListener=函数(id,模式){
var radioButton=document.getElementById(id);
var me=这个;
radioButton.addEventListener('单击',函数()){
me.travelMode=mode;
我。路线();
});
};
AutoCompletedDirectionShandler.prototype.setupPlaceChangedListener=函数(自动完成,模式){
var me=这个;
autocomplete.bindTo('bounds',this.map);
autocomplete.addListener('place\u changed',function(){
var place=autocomplete.getPlace();
如果(!place.place\u id){
警告(“请从下拉列表中选择一个选项”);
返回;
}
如果(模式=='ORIG'){
me.originPlaceId=place.place\u id;
}否则{
me.destinationPlaceId=place.place\u id;
}
我。路线();
});
};
AutoCompletedDirectionShandler.prototype.route=函数(){
如果(!this.originPlaceId | |!this.destinationPlaceId){
返回;
}
var me=这个;
此路径为.DirectionService.route({
原点:{'placeId':this.originPlaceId},
目标:{'placeId':this.destinationPlaceId},
travelMode:this.travelMode
},功能(响应、状态){
如果(状态=='OK'){
me.directionsDisplay.setDirections(响应);
}否则{
window.alert('由于'+状态,指示请求失败);
}
});
};
/************************************/
$(文档).ready(函数(){
$(“#要提交的按钮”)。单击(函数(){
origin_addr=$(“#origin input”).val();
目的地地址=$(“#目的地输入”).val();
$.ajax({
类型:“POST”,
url:“maps.exe.php”,
数据:{
来源地址:来源地址,
目的地地址:目的地地址
},
成功:功能(响应){
警报(响应);
window.location.href='test resp.php?'+响应;
}
});
返回false;
});
});
/*maps.exe.php*/

<?php

$origin_address = $_POST['origin_address'];
$destination_address = $_POST['destination_address'];

echo"origin=$origin_address&destination=$destination_address";

?>

/*test-resp.php*/

<?php

$origin_address = $_GET['origin'];
$destination_address = $_GET['destination'];

echo"[ origin : $origin_address / destination = $destination_address ]";

?>

/*