How to pass JavaScript variables to PHP?

2018-12-30 23:00发布

I want to pass JavaScript variables to PHP using a hidden input in a form.

But I can't get the value of $_POST['hidden1'] into $salarieid. Is there something wrong?

Here is the code:

<script type="text/javascript">
// view which the user has chosen
function func_load3(name){
    var oForm = document.forms["myform"];
    var oSelectBox = oForm.select3;
    var iChoice = oSelectBox.selectedIndex;
    //alert("you have choosen: " + oSelectBox.options[iChoice].text );
    //document.write(oSelectBox.options[iChoice].text);
    var sa = oSelectBox.options[iChoice].text;
    document.getElementById("hidden1").value = sa;
}
</script>

<form name="myform" action="<?php echo $_SERVER['$PHP_SELF']; ?>" method="POST">
        <input type="hidden" name="hidden1" id="hidden1"  />
</form>

<?php
   $salarieid = $_POST['hidden1'];
   $query = "select * from salarie where salarieid = ".$salarieid;
   echo $query;
   $result = mysql_query($query);
?>

<table>
   code for display the query result. 
</table>

12条回答
旧人旧事旧时光
2楼-- · 2018-12-30 23:50

Here is the Working example: Get javascript variable value on the same page in php.

<script>
var p1 = "success";
</script>

<?php
echo "<script>document.writeln(p1);</script>";
?>
查看更多
裙下三千臣
3楼-- · 2018-12-30 23:51

You cannot pass variable values from the current page javascript to the current page PHP code... PHP code runs at the server side and it doesn't know anything about what is going on on the client side.

You need to pass variables to PHP code from html-form using another mechanism, such as submitting form on GET or POST methods.

<DOCTYPE html>
<html>
  <head>
    <title>My Test Form</title>
  </head>

  <body>
    <form method="POST">
      <p>Please, choose the salary id to proceed result:</p>
      <p>
        <label for="salarieids">SalarieID:</label>
        <?php
          $query = "SELECT * FROM salarie";
          $result = mysql_query($query);
          if ($result) :
        ?>
        <select id="salarieids" name="salarieid">
          <?php
            while ($row = mysql_fetch_assoc($result)) {
              echo '<option value="', $row['salaried'], '">', $row['salaried'], '</option>'; //between <option></option> tags you can output something more human-friendly (like $row['name'], if table "salaried" have one) 
            }
          ?>
        </select>
        <?php endif ?>
      </p>
      <p>
        <input type="submit" value="Sumbit my choice"/>
      </p>
    </form>

    <?php if isset($_POST['salaried']) : ?>
      <?php
        $query = "SELECT * FROM salarie WHERE salarieid = " . $_POST['salarieid'];
        $result = mysql_query($query);
        if ($result) :
      ?>
        <table>
          <?php
            while ($row = mysql_fetch_assoc($result)) {
              echo '<tr>';
              echo '<td>', $row['salaried'], '</td><td>', $row['bla-bla-bla'], '</td>' ...; // and others
              echo '</tr>';
            }
          ?>
        </table>
      <?php endif?>
    <?php endif ?>
  </body>
</html>
查看更多
一个人的天荒地老
4楼-- · 2018-12-30 23:55

Your code has a few things wrong with it.

  • You define a JavaScript function, func_load3(), but do not call it.
  • Your function is defined in the wrong place. When it is defined in your page, the HTML objects it refers to have not yet been loaded. Most JavaScript code checks whether the document is fully loaded before executing, or you can just move your code past the elements it refers to in the page.
  • Your form has no means to submit it. It needs a submit button.
  • You do not check whether your form has been submitted.

It is possible to set a JavaScript variable in a hidden variable in a form, then submit it, and read the value back in PHP. Here is a simple example that shows this:

<?php
if (isset($_POST['hidden1'])) {
   echo "You submitted {$_POST['hidden1']}";
   die;
}

echo <<<HTML
   <form name="myform" action="{$_SERVER['PHP_SELF']}" method="post" id="myform">
      <input type="submit" name="submit" value="Test this mess!" />
      <input type="hidden" name="hidden1" id="hidden1" />
   </form>

   <script type="text/javascript">
      document.getElementById("hidden1").value = "This is an example";
   </script>
HTML;
?>
查看更多
残风、尘缘若梦
5楼-- · 2018-12-30 23:55

May be you could use jquery serialize() method so that everything will be at one go.

var data=$('#myForm').serialize();

//this way you could get the hidden value as well in the server side.

查看更多
还给你的自由
6楼-- · 2018-12-30 23:57

This obviously solution was not mentioned earlier. You can also use cookies to pass data from the browser back to the server.

Just set a cookie with the data you want to pass to PHP using javascript in the browser.

Then, simply read this cookie on the PHP side.

查看更多
看淡一切
7楼-- · 2018-12-30 23:58

just save it in a cookie:

$(document).ready(function () {
  createCookie("height", $(window).height(), "10");
});

function createCookie(name, value, days) {
  var expires;
  if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    expires = "; expires=" + date.toGMTString();
  } else {
   expires = "";
  }
  document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";
}

and then read it with php

<?PHP
   $_COOKIE["height"];
?>

its not a pretty solution, but it works. Cheers.

查看更多
登录 后发表回答