简体   繁体   English

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

[英]Pass Javascript and PHP variables through PHP Form

Been searching all day, found items similar but completely stuck... 整天都在搜索,发现相似但完全卡住的物品...

I want to pass a Google Maps Autocomplete Result (latlng) into a PHP Form along with PHP variables through one submit (not two buttons, ie to put JS variable in hidden field then submit form via submit button) 我想将Google Maps自动完成结果(latlng)与PHP变量一起通过一个提交传递给PHP表单(而不是两个按钮,即将JS变量放在隐藏字段中,然后通过提交按钮提交表单)

Code at present: 目前的代码:

    <?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...    
}    

?>

Then: 然后:

<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>

Finally: 最后:

<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>

I'd preferably like when I hit the Submit button it stores Google Maps result into hidden, submits form to same page then I can pull all php vars and store. 我希望当我单击“提交”按钮时,它会将Google Maps结果存储为隐藏,将表单提交到同一页面,然后可以拉出所有php vars并存储。 I'm open to an approach which upon submit puts the javascript part into the url where I can pull PHP vars via POST and just GET the Google Result in the URL. 我愿意接受一种方法,提交后将javascript部分放到url中,我可以通过POST提取PHP变量,而只需在URL中获取Google结果。

The only thing I can see which isn't working in the above is the form gets submitted before my codeAddress() has completed. 我唯一可以看到的在上面无效的是在我的codeAddress()完成之前提交了表单。 As if I put return false to prevent form submit it updates my hidden field. 好像我把return false阻止表单提交一样,它更新了我的隐藏字段。

Thanks in advance! 提前致谢!

To be honest, I'm not very familiar with Google's Geocoding api, but there are a couple of ways you can do this. 老实说,我对Google的Geocoding api不太熟悉,但是有两种方法可以做到这一点。

First Method 第一种方法

Append hidden input elements inside your form. 在表单内附加隐藏的输入元素。 This is probably the closest to what you are describing in your question. 这可能是最接近您在问题中描述的内容。

Here is a simplified form: 这是一个简化的形式:

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

Adding the return doSubmit(); 添加return doSubmit(); means that you can call that function, and cancel sending the form if you need to. 表示您可以调用该函数,并在需要时取消发送表单。

Here is the accompanying javascript: 这是随附的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.
}

If using jQuery, this becomes easier. 如果使用jQuery,这将变得更加容易。 You don't need to add the onSubmit field to the form. 您无需将onSubmit字段添加到表单。 Just assign a unique name, or an id to the submit button. 只需为“提交”按钮分配一个唯一的名称或一个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 + "' />"
       );
    });

}); });

Here is a simple test php file: 这是一个简单的测试php文件:

//test.php
<?php

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

When you click on the button, it will append a hidden input to the form, and send that along with the rest of the POST data. 当您单击按钮时,它将隐藏的输入追加到表单,并将其与其余的POST数据一起发送。 You can assign array type values to form names, and it will convert it to be an array in the PHP $_POST array. 您可以将数组类型值分配给表单名称,并将其转换为PHP $_POST数组中的数组。

This example will print "LAT IS: 42" when you click the button. 当单击按钮时,此示例将打印“ LAT IS:42”。

Second Method 第二种方法

This is the best one. 这是最好的。 Use ajax and json with jQuery (ajax can be done in raw javascript, but it isn't fun ! 在jQuery中使用ajax和json(ajax可以在原始javascript中完成,但这不好玩

For this, I will use a simpler form, and add a div: 为此,我将使用一个更简单的形式,并添加一个div:

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

The php just echos $_POST["geo"]["lat"] . php只是回显$_POST["geo"]["lat"]

Here is the javascript: 这是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>"); 
            }
        });
    });
});

In a nutshell, this is how easy ajax is. 简而言之,这就是ajax的简易性。 Clicking the submit button in this example will set the html of the div to 42. 在此示例中,单击提交按钮会将div的html设置为42。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM