Skip to content
Advertisement

Pass PHP variable from HTML form to Javascript

could you help me pass a variable that was taken from a html form into javascript.

The form asks for the tablename

  <br>
    New tablename:<br>
    <input  type="text"  name="table">

It is passed through PHP:

if (isset($_POST['submit'])) {
    $user = $_POST['user'];
    $password = $_POST['password'];
    $table = $_POST['table'];
    $geometry = $_POST['geom'];
  
}

A first action is underway, and created successfully: the Geoserver postgis table is created through PHP curl (entire code below)

then the javascript tries to get $table with a PHP insert; this will help it load the newly created postgis Geoserver table from the PHP, into the WFST javascript ;

    <?php
echo "var thedata = " .$table. ";n";
?>

  var wfstPoly = new L.WFST({
    url: 'https://mappingforyou.eu/geoserver/ows',
    typeNS: 'opendata',
    typeName: thedata,

But this code doesn’t work:

    <?php
echo "var thedata = " .$table. ";n";
?>

— The code works fine except for the thedata javascript variable. The entire form:

<!DOCTYPE  html>
<html>
    <body>
    
        <h2>PG GS input test</h2>

        <form  method="POST"  action="test1.php">
            User:<br>
            <input  type="text"  name="user">
            <br>
            Password:<br>
            <input  type="password"  name="password">
          <br>
            New tablename:<br>
            <input  type="text"  name="table">
      
        <input type="radio" name="geom" id="Point" value="Point" />
<label for="Point">Point</label>

<input type="radio" name="geom" id="MultiLineString" value="MultiLineString" />
<label for="MultiLine">Line</label>

           <input type="radio" name="geom" id="MultiPolygon" value="MultiPolygon" />
<label for="MultiPolygon">Area</label>

                <br><br>
            <input  type="submit"  name="submit">

    </form>
    </body>
</html>

Into this javascript test1.php page:

<!DOCTYPE html>
<html>
<head lang="en">
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.2.0/leaflet.css"/>
  <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css"/>
  <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.toolbar.js/0.3.0/leaflet.toolbar.css" />
  <style>
    html, body, #map {
      margin: 0;
      height: 100%;
      width: 100%;
    }
  </style>
  <title>Leaflet-WFST polygon demo</title>
</head>
<body>
<div id="map"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.2.0/leaflet.js"></script>
<link rel="stylesheet" href="https://mappingforyou.eu/javascript/leaflet.draw.css" /> 
<script src="https://mappingforyou.eu/javascript/leaflet.draw-src.js"></script>
<link type="text/css" rel="stylesheet" href="https://mappingforyou.eu/javascript/leaflet-easybutton.css" />
<script type="text/javascript" src="https://mappingforyou.eu/javascript/leaflet-easybutton.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/proj4js/2.4.4/proj4.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/proj4leaflet/1.0.2/proj4leaflet.js"></script>
<script src="https://mappingforyou.eu/javascript/leaflet-wfst.src.js"></script>


<script>

function jsFunction(){

    <?php
echo "var thedata = " .$table. ";n";
?>

  var map = L.map('map', {editable: true}).setView([48.5, 2], 10);
  // add an OpenStreetMap tile layer
  L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
  }).addTo(map);

  var wfstPoly = new L.WFST({
    url: 'http://localhost:8080/geoserver/ows',
    typeNS: 'workspace',
    typeName: thedata,
    crs: L.CRS.EPSG4326,
    geometryField: 'geom',
    style: {
      color: 'blue',
      weight: 2
    }
  }).addTo(map)
    .once('load', function () {
      map.fitBounds(wfstPoly);
    });

    ////// draw and edit

    var drawControl = new L.Control.Draw({
    draw:{circle:false, circlemarker:false, rectangle:false,
          },
    edit:{featureGroup: wfstPoly } });
map.addControl(drawControl);

map.on('draw:created', function (e) {
    var layer = e.layer;
    wfstPoly.addLayer(layer)});

map.on('draw:edited', function (e) {
    var layers = e.layers;
    layers.eachLayer( function (layer) {
        wfstPoly.editLayer(layer);
        })

        });

    // Save button
L.easyButton('fa-save', function () {
         wfstPoly.save();
     }, 'Save changes').addTo(map);

}

</script>

<?php
    // Open log file
    $logfh = fopen("GeoserverPHP.log", 'w') or die("can't open log file");

    // Initiate cURL session
    $service = "http://localhost:8080/geoserver/rest"; // replace with your URL
    $ws = "workspace";
    $ds = "database";
    $request = "/workspaces/" . $ws . "/datastores/" . $ds . "/featuretypes";
    $url = $service . $request;
    $ch = curl_init($url);

if (isset($_POST['submit'])) {
    $user = $_POST['user'];
    $password = $_POST['password'];
    $table = $_POST['table'];
    $geometry = $_POST['geom'];
  
}

define("GEOSERVER_REST_HOST", "http://localhost:8080/geoserver/rest");
define("GEOSERVER_USER", "admin:password");


    // Optional settings for debugging
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //option to return string
    curl_setopt($ch, CURLOPT_VERBOSE, true);
    curl_setopt($ch, CURLOPT_STDERR, $logfh); // logs curl messages

    //Required POST request settings
    curl_setopt($ch, CURLOPT_POST, True);
    //$passwordStr = "admin:geoserver"; // replace with your username:password
    curl_setopt($ch, CURLOPT_USERPWD, GEOSERVER_USER);

    //POST data
    curl_setopt($ch, CURLOPT_HTTPHEADER,
              array("Content-type: text/xml"));
    $xmlStr = "<featureType>";
    $xmlStr .= "<name>".$table."</name>";
    $xmlStr .= "<nativeName>".$table."</nativeName>";
    $xmlStr .= "<title>".$table."</title>";
    $xmlStr .= "<srs>EPSG:4326</srs>";
    $xmlStr .= "<attributes>";
    $xmlStr .= "<attribute>";
    $xmlStr .= "<name>geom</name>";
    $xmlStr .= "<binding>com.vividsolutions.jts.geom.".$geometry."</binding>";
    $xmlStr .= "</attribute>";
    $xmlStr .= "<attribute>";
    $xmlStr .= "<name>description</name>";
    $xmlStr .= "<binding>java.lang.String</binding>";
    $xmlStr .= "</attribute>";
    $xmlStr .= "<attribute>";
    $xmlStr .= "<name>timestamp</name>";
    $xmlStr .= "<binding>java.util.Date</binding>";
    $xmlStr .= "</attribute>";
    $xmlStr .= "</attributes>";
    $xmlStr .= "</featureType>";
    
   
    curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlStr);

    //POST return code
    $successCode = 201;

    $buffer = curl_exec($ch); // Execute the curl request

    // Check for errors and process results
    $info = curl_getinfo($ch);
    if ($info['http_code'] != $successCode) {
      $msgStr = "# Unsuccessful cURL request to ";
      $msgStr .= $url." [". $info['http_code']. "]n";
      fwrite($logfh, $msgStr);
    } else {
      $msgStr = "# Successful cURL request to ".$url."n";
      fwrite($logfh, $msgStr);
    }
    fwrite($logfh, $buffer."n");

    curl_close($ch); // free resources if curl handle will not be reused
    fclose($logfh);  // close logfile
    
    echo '<script type="text/javascript">jsFunction();</script>';

    

        return $success;

?>


</body>
</html>

Advertisement

Answer

In the code you provided, this:

if (isset($_POST['submit'])) {
    $user = $_POST['user'];
    $password = $_POST['password'];
    $table = $_POST['table'];
    $geometry = $_POST['geom'];
  
}

…comes after this:

echo "var thedata = " .$table. ";n";

The initial assignment of PHP variable $table needs to come before it is used.

And if the table name, provided by the form text input, is a string, $table needs to be quoted for when it gets assigned to the Javascript variable thedata:


For example:

function jsFunction(){

<?php

if (isset($_POST['submit'])) {
    $user = $_POST['user'];
    $password = $_POST['password'];
    $table = $_POST['table'];
    $geometry = $_POST['geom'];
  
}

// ...

echo "var thedata = "" .$table. "";n";

?>

<!-- ... -->

Keep in mind, PHP executes on the server, and the resulting text, containing HTML, Javascript, CSS, is sent to the browser through HTTP. The browser never gets PHP code. The browser only gets HTML, Javascript, and CSS. Once the browser gets these from the server it evaluates the Javascript and renders the HTML and CSS.

This, on the server:

function jsFunction(){

<?php

if (isset($_POST['submit'])) {
    $user = $_POST['user'];
    $password = $_POST['password'];
    $table = $_POST['table'];
    $geometry = $_POST['geom'];

}

// ...

echo "var thedata = "" .$table. "";n";

?>

<!-- ... -->

…is executed resulting in this:

function jsFunction(){

var thedata = "user provided table name";


<!-- ... -->

…which is then sent as text to the browser.

I elaborate further on the distinct PHP and Javascript execution contexts here: https://stackoverflow.com/a/72023066/2743458

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement