通过PHP表单传递Javascript和PHP变量

时间:2014-10-05 06:03:46

标签: javascript php ajax

一整天都在搜索,发现类似但完全卡住的物品...

我想通过一个提交(而不是两个按钮,即将JS变量放入隐藏字段,然后通过提交按钮提交表单)将Google地图自动填充结果(latlng)与PHP变量一起传递到PHP表单中

目前的代码:

    <?php    

if (isset($_POST['submit'])) {    
  // echo vars if they are working...
  echo "passed data <br>";
  echo $_POST['first_name'] . "<br>";
  echo $_POST['geocode'] . "<br>";    

  // Get variables, check data and store into DB...    
}    

?>

然后:

<script type="text/javascript">

  var geocoder;

  function initialize() {

    // Search options
    var searchOptions = { 
      componentRestrictions : {country: 'nz'},
      types: ['geocode']
    };

    var input = document.getElementById('pac-input');

    var autocomplete = new google.maps.places.Autocomplete(input, searchOptions);

    geocoder = new google.maps.Geocoder();

  }

  function codeAddress() {

    var address = document.getElementById('pac-input').value;

    geocoder.geocode( { 'address': address}, function(results, status) {    
      if (status == google.maps.GeocoderStatus.OK) {        
        document.getElementById('geocode').value = (results[0].geometry.location);             
      } else {
        //alert('Geocode was not successful for the following reason: ' + status);
      }

    });

  }

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

  function submitthis() {

    codeAddress();

  }

  </script>

  <script>

  $(function(){ // Document Ready

  });

  </script>

最后:

<form id="myForm" name="myForm" action="google-text-input.php" method="post" >

    First Name<input name="first_name" type="text"><br>

    Address<input id="pac-input" class="controls" type="text" placeholder="Search Box"><br>



    <input id="geocode" name="geocode" type="text" value="null"><br> <!-- to be hidden -->

    <input name="submit" type="submit" value="Submit" onclick="submitthis()"><br>


  </form>

我最喜欢当我点击“提交”按钮时,它会将Google地图结果存储到隐藏状态,将表单提交到同一页面然后我可以提取所有的php变量和存储。我开放了一种方法,在提交后将javascript部分放入url,我可以通过POST拉取PHP变量,只需在URL中获取Google Result。

我唯一能看到的是上面没有工作的是在我的codeAddress()完成之前提交的表单。好像我把return false设置为阻止表单提交更新我的隐藏字段。

提前致谢!

1 个答案:

答案 0 :(得分:0)

说实话,我对Google的Geocoding api并不是很熟悉,但有几种方法可以做到这一点。

第一种方法

在表单中附加隐藏的输入元素。这可能与您在问题中描述的内容最接近。

这是一个简化的表格:

<form name="testForm" action="test.php" 
  method="post" onSubmit="return doSubmit();">
    <input type="submit" name="submit" />
</form>

添加return doSubmit();表示您可以调用该功能,并在需要时取消发送表单。

以下是随附的javascript:

function doSubmit() {
    var latval = 42; // Use the geolocation values you want here.
    var lat = document.createElement("input");
    lat.setAttribute("type", "hidden");
    lat.setAttribute("value", latval);
    lat.setAttribute("name", "geo[lat]");
    document.forms["testForm"].appendChild(lat);
    return true;
    //Note: to stop the form from submitting, you can just return false.
}

如果使用jQuery,这会变得更容易。您不需要将onSubmit字段添加到表单中。只需为提交按钮指定唯一的名称或ID即可。

$(document.ready(function() {
    $("input[name=submit]").click(function(e) {
       var latVal = 42; // Get geo vals here.
       $("form[name=testForm]").appendChild(
           "<input type='hidden' name='geo[lat]' value='" + latVal + "' />"
       );
    });

});

这是一个简单的测试php文件:

//test.php
<?php

if (isset($_POST["geo"])) {
    echo "LAT IS: ".$_POST["geo"]["lat"];
}
?>

当您单击该按钮时,它会向表单附加一个隐藏的输入,并将其与其余的POST数据一起发送。您可以将数组类型值分配给表单名称,并将其转换为PHP $_POST数组中的数组。

此示例将打印&#34; LAT IS:42&#34;当你点击按钮时。

第二种方法

这是最好的一个。将ajax和json与jQuery一起使用(ajax可以在原始javascript中完成,但它isn't fun

为此,我将使用更简单的表格,并添加div:

<form name="testForm">
    <input type="submit" name="submit" />
</form>
<div id="output"></div>

php只是回声$_POST["geo"]["lat"]

这是javascript:

$(document).ready(function() {
    $("form[name=testForm]").submit(function (e) {
        // Prevent form from submitting.
        e.preventDefault();
        // Create a js object.
        var jso = {};
        // Add a geo object.
        jso['geo'] = {};
        // Define its lat value.
        jso['geo']['lat'] = 42;
        // Add all other values you want to POST in the method.
        // You can also just do jso.lat = 42, then change the php accordingly.
        // Send the ajax query.
        $.ajax({
            url: 'test.php',
            type: 'POST',
            data: jso,
            success: function(data, status) {
                $("#output").html("<p>" + data + "</p>"); 
            }
        });
    });
});

简而言之,这就是ajax的容易程度。单击此示例中的提交按钮会将div的html设置为42。

相关问题