Pass PHP variable from HTML form to Javascript

Vincent Dc

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

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

How to pass a variable from an html form to a php script?

From Dev

Pass variable from PHP into HTML

From Dev

Pass a variable from JavaScript to PHP

From Dev

Pass Unique PHP Variable to Javascript via Form

From Dev

How to pass input variable from HTML Form

From Dev

Send HTML form with Javascript variable to PHP -> Mysql

From Dev

Pass a flask variable from javascript to html

From Dev

how to pass variable from html to ajax/javascript

From Dev

Operation with Javascript with a variable from a form in PHP

From Dev

Post variable from JavaScript to PHP with form

From Dev

how to pass string variable of JavaScript to html form input,

From Dev

Pass variable PHP/HTML

From Dev

Javascript to pass a variable to HTML

From PHP

How to pass and put variable from a php page into a another page(form)?

From Dev

How to pass variable from actionCreate to _form.php?

From Dev

HTML form with php variable

From PHP

Get variable to pass to php form

From Dev

HTML Form to JavaScript variable

From Dev

Pass PHP variable from html to php and email template

From Dev

Pass Data from HTML Form to MySQL Database using PHP

From Mysql

Obtain Date value from HTML form and pass it in PHP

From Dev

Get a return from JQuery to a PHP variable in a simple HTML PHP Form

From Dev

How to pass a user entered form value from html to javascript?

From Dev

Pass variable from input to form

From Dev

pass php variable through name in javascript appended to html

From Dev

pass JavaScript variable to HTML input box and (to use in PHP file)

From Dev

Variable from form to Javascript

From Dev

How to pass php variable to html template from Database in WordPress

From Javascript

Pass a variable to Javascript directly from <script> HTML tag

Related Related

  1. 1

    How to pass a variable from an html form to a php script?

  2. 2

    Pass variable from PHP into HTML

  3. 3

    Pass a variable from JavaScript to PHP

  4. 4

    Pass Unique PHP Variable to Javascript via Form

  5. 5

    How to pass input variable from HTML Form

  6. 6

    Send HTML form with Javascript variable to PHP -> Mysql

  7. 7

    Pass a flask variable from javascript to html

  8. 8

    how to pass variable from html to ajax/javascript

  9. 9

    Operation with Javascript with a variable from a form in PHP

  10. 10

    Post variable from JavaScript to PHP with form

  11. 11

    how to pass string variable of JavaScript to html form input,

  12. 12

    Pass variable PHP/HTML

  13. 13

    Javascript to pass a variable to HTML

  14. 14

    How to pass and put variable from a php page into a another page(form)?

  15. 15

    How to pass variable from actionCreate to _form.php?

  16. 16

    HTML form with php variable

  17. 17

    Get variable to pass to php form

  18. 18

    HTML Form to JavaScript variable

  19. 19

    Pass PHP variable from html to php and email template

  20. 20

    Pass Data from HTML Form to MySQL Database using PHP

  21. 21

    Obtain Date value from HTML form and pass it in PHP

  22. 22

    Get a return from JQuery to a PHP variable in a simple HTML PHP Form

  23. 23

    How to pass a user entered form value from html to javascript?

  24. 24

    Pass variable from input to form

  25. 25

    pass php variable through name in javascript appended to html

  26. 26

    pass JavaScript variable to HTML input box and (to use in PHP file)

  27. 27

    Variable from form to Javascript

  28. 28

    How to pass php variable to html template from Database in WordPress

  29. 29

    Pass a variable to Javascript directly from <script> HTML tag

HotTag

Archive