简体   繁体   中英

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)

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

The only thing I can see which isn't working in the above is the form gets submitted before my codeAddress() has completed. As if I put return false to prevent form submit it updates my hidden field.

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.

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(); means that you can call that function, and cancel sending the form if you need to.

Here is the accompanying 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. You don't need to add the onSubmit field to the form. Just assign a unique name, or an id to the submit button.

$(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:

//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. You can assign array type values to form names, and it will convert it to be an array in the PHP $_POST array.

This example will print "LAT IS: 42" when you click the button.

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 !

For this, I will use a simpler form, and add a div:

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

The php just echos $_POST["geo"]["lat"] .

Here is the 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. Clicking the submit button in this example will set the html of the div to 42.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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