如何将JavaScript变量传递给PHP?

时间:2021-07-10 15:12:48

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

我想使用表单中的隐藏输入将JavaScript变量传递给PHP。

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

但我无法将$_POST的值(hidden1)变成$salarieid。有什么错了吗?

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>

11 个解决方案

#1


69  

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.

不能将变量值从当前页面javascript传递到当前页面PHP代码……PHP代码在服务器端运行,它不知道客户端发生了什么。

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

您需要使用另一种机制将变量从html表单传递到PHP代码,例如在GET或POST方法上提交表单。

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

#2


17  

There are several ways of passing variables from javascript to php (not the current page, of course)

将变量从javascript传递到php有几种方法(当然不是当前页面)

You could:

你可以:

  1. send the information in a form as stated here, (will result in a page refresh)
  2. 按此处所述的形式发送信息(将导致页面刷新)
  3. pass it in ajax (several posts on here about that) (without a page refresh)
  4. 在ajax中传递(这里有几个帖子)(没有页面刷新)
  5. make a http request via a XMLHttpRequest request (without a page refresh) like this:
  6. 通过XMLHttpRequest请求(不刷新页面)发出http请求如下:

 if (window.XMLHttpRequest){
     xmlhttp=new XMLHttpRequest();
 }

else{
     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
 }

 var PageToSendTo = "nowitworks.php?";
 var MyVariable = "variableData";
 var VariablePlaceholder = "variableName=";
 var UrlToSend = PageToSendTo + VariablePlaceholder + MyVariable;

 xmlhttp.open("GET", UrlToSend, false);
 xmlhttp.send();

I'm sure this could be made to look fancier and loop through all the variables and whatnot - but I've kept it basic as to make it easier to understand for the novices.

我确信这可以让它看起来更漂亮,并循环遍历所有的变量和其他的东西——但我一直保持它的基本原理,以便让初学者更容易理解。

#3


13  

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

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

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

这不是一个很好的解决方案,但它确实有效。欢呼。

#4


5  

PHP runs on the server before the page is sent to the user, JavaScript is run on the user's computer once it is received, so the PHP script has already executed.

PHP在页面发送给用户之前在服务器上运行,JavaScript在用户的计算机上运行,因此PHP脚本已经执行。

If you want to pass a JavaScript value to a PHP script, you'd have to do an XMLHttpRequest to send the data back to the server.

如果希望将JavaScript值传递给PHP脚本,则必须执行XMLHttpRequest将数据发送回服务器。

Here's a previous question that you can follow for more information: Ajax Tutorial

这里有一个问题,您可以根据它获得更多信息:Ajax教程

Now if you just need to pass a form value to the server, you can also just do a normal form post, that does the same thing, but the whole page has to be refreshed.

现在,如果您只需要将一个表单值传递给服务器,您还可以做一个普通的表单post,它做同样的事情,但是整个页面必须刷新。

<?php
if(isset($_POST))
{
  print_r($_POST);
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
  <input type="text" name="data" value="1" />
  <input type="submit" value="Submit" />
</form>

Clicking submit will submit the page, and print out the submitted data.

单击submit将提交页面,并打印提交的数据。

#5


5  

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

这里有一个工作示例:在php的同一页面上获取javascript变量值。

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

<?php
echo "<script>document.writeln(p1);</script>";
?>

#6


5  

We can easily pass values even on same/ different pages using the cookies shown in the code as follows (In my case, I'm using it with facebook integration) -

我们可以很容易地在相同/不同的页面上传递值,使用代码中显示的cookie(在我的例子中,我使用它与facebook集成)-

function statusChangeCallback(response) {
        console.log('statusChangeCallback');
                if (response.status === 'connected') {
                // Logged into your app and Facebook.
                FB.api('/me?fields=id,first_name,last_name,email', function(result) {
                    document.cookie = "fbdata = " + result.id + "," + result.first_name + "," + result.last_name + "," + result.email;
                    console.log(document.cookie);
                });
            }
        }

And I've accessed it (in any file) using -

我用-访问了它(在任何文件中)

<?php 
    if(isset($_COOKIE['fbdata'])) { 
        echo "welcome ".$_COOKIE['fbdata'];
    }
?>

#7


5  

I was trying to figure this out myself and then realized that the problem is that this is kind of a backwards way of looking at the situation. Rather than trying to pass things from JavaScript to php, maybe it's best to go the other way around, in most cases. PHP code executes on the server and creates the html code (and possibly java script as well). Then the browser loads the page and executes the html and java script.

我试着自己解决这个问题,然后意识到问题是这是一种回顾情况的方式。与其尝试从JavaScript传递到php,不如在大多数情况下,最好是相反的方式。PHP代码在服务器上执行并创建html代码(可能还有java脚本)。然后浏览器加载页面并执行html和java脚本。

It seems like the sensible way to approach situations like this is to use the PHP to create the JavaScript and the html you want and then to use the JavaScript in the page to do whatever PHP can't do. It seems like this would give you the benefits of both PHP and JavaScript in a fairly simple and straight forward way.

处理这种情况的明智方法似乎是使用PHP创建您想要的JavaScript和html,然后在页面中使用JavaScript完成PHP不能完成的任何事情。看起来这将以一种相当简单和直接的方式为您提供PHP和JavaScript的好处。

One thing I've done that gives the appearance of passing things to PHP from your page on the fly is using the html image tag to call on PHP code. Something like this:

我所做的一件事情就是在页面上动态地将东西传递给PHP,那就是使用html图像标记来调用PHP代码。是这样的:

<img src="pic.php">

The PHP code in pic.php would actually create html code before your web page was even loaded, but that html code is basically called upon on the fly. The php code here can be used to create a picture on your page, but it can have any commands you like besides that in it. Maybe it changes the contents of some files on your server, etc. The upside of this is that the php code can be executed from html and I assume JavaScript, but the down side is that the only output it can put on your page is an image. You also have the option of passing variables to the php code through parameters in the url. Page counters will use this technique in many cases.

图片中的PHP代码。php实际上会在加载web页面之前创建html代码,但是html代码基本上是动态调用的。这里的php代码可以用来在页面上创建图片,但是它可以有任何你喜欢的命令,除此之外。它可能会改变服务器上的一些文件的内容,等等。它的好处是php代码可以从html执行,我假设是JavaScript,但是它的缺点是,它只能输出图像。您还可以通过url中的参数向php代码传递变量。页面计数器将在许多情况下使用这种技术。

#8


2  

Is your function, which sets the hidden form value, being called? It is not in this example. You should have no problem modifying a hidden value before posting the form back to the server.

您的函数是否设置了隐藏的表单值?这个例子里没有。在将表单发送回服务器之前,您应该没有任何修改隐藏值的问题。

#9


2  

Here's how I did it (needed to insert a local timezone into php:

我是这样做的(需要在php中插入一个本地时区:

<?php

ob_start();
?>
<script type="text/javascript">

var d = new Date(); 
document.write(d.getTimezoneOffset());     
</script>
<?php

$offset = ob_get_clean();

print_r($offset);

#10


1  

Your code has a few things wrong with it.

您的代码有一些问题。

  • You define a JavaScript function, func_load3(), but do not call it.
  • 定义一个JavaScript函数func_load3(),但不要调用它。
  • 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.
  • 函数定义在错误的位置。当它在您的页面中定义时,它所引用的HTML对象还没有加载。大多数JavaScript代码在执行之前检查文档是否已被完全加载,或者您可以将代码移动到它在页面中引用的元素之上。
  • 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:

可以在表单中的隐藏变量中设置一个JavaScript变量,然后提交它,然后在PHP中读取该值。这里有一个简单的例子可以说明这一点:

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

#11


1  

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

可能您可以使用jquery serialize()方法,这样一切就会一蹴而就。

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

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

//通过这种方式,您还可以在服务器端获得隐藏值。

#1


69  

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.

不能将变量值从当前页面javascript传递到当前页面PHP代码……PHP代码在服务器端运行,它不知道客户端发生了什么。

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

您需要使用另一种机制将变量从html表单传递到PHP代码,例如在GET或POST方法上提交表单。

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

#2


17  

There are several ways of passing variables from javascript to php (not the current page, of course)

将变量从javascript传递到php有几种方法(当然不是当前页面)

You could:

你可以:

  1. send the information in a form as stated here, (will result in a page refresh)
  2. 按此处所述的形式发送信息(将导致页面刷新)
  3. pass it in ajax (several posts on here about that) (without a page refresh)
  4. 在ajax中传递(这里有几个帖子)(没有页面刷新)
  5. make a http request via a XMLHttpRequest request (without a page refresh) like this:
  6. 通过XMLHttpRequest请求(不刷新页面)发出http请求如下:

 if (window.XMLHttpRequest){
     xmlhttp=new XMLHttpRequest();
 }

else{
     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
 }

 var PageToSendTo = "nowitworks.php?";
 var MyVariable = "variableData";
 var VariablePlaceholder = "variableName=";
 var UrlToSend = PageToSendTo + VariablePlaceholder + MyVariable;

 xmlhttp.open("GET", UrlToSend, false);
 xmlhttp.send();

I'm sure this could be made to look fancier and loop through all the variables and whatnot - but I've kept it basic as to make it easier to understand for the novices.

我确信这可以让它看起来更漂亮,并循环遍历所有的变量和其他的东西——但我一直保持它的基本原理,以便让初学者更容易理解。

#3


13  

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

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

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

这不是一个很好的解决方案,但它确实有效。欢呼。

#4


5  

PHP runs on the server before the page is sent to the user, JavaScript is run on the user's computer once it is received, so the PHP script has already executed.

PHP在页面发送给用户之前在服务器上运行,JavaScript在用户的计算机上运行,因此PHP脚本已经执行。

If you want to pass a JavaScript value to a PHP script, you'd have to do an XMLHttpRequest to send the data back to the server.

如果希望将JavaScript值传递给PHP脚本,则必须执行XMLHttpRequest将数据发送回服务器。

Here's a previous question that you can follow for more information: Ajax Tutorial

这里有一个问题,您可以根据它获得更多信息:Ajax教程

Now if you just need to pass a form value to the server, you can also just do a normal form post, that does the same thing, but the whole page has to be refreshed.

现在,如果您只需要将一个表单值传递给服务器,您还可以做一个普通的表单post,它做同样的事情,但是整个页面必须刷新。

<?php
if(isset($_POST))
{
  print_r($_POST);
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
  <input type="text" name="data" value="1" />
  <input type="submit" value="Submit" />
</form>

Clicking submit will submit the page, and print out the submitted data.

单击submit将提交页面,并打印提交的数据。

#5


5  

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

这里有一个工作示例:在php的同一页面上获取javascript变量值。

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

<?php
echo "<script>document.writeln(p1);</script>";
?>

#6


5  

We can easily pass values even on same/ different pages using the cookies shown in the code as follows (In my case, I'm using it with facebook integration) -

我们可以很容易地在相同/不同的页面上传递值,使用代码中显示的cookie(在我的例子中,我使用它与facebook集成)-

function statusChangeCallback(response) {
        console.log('statusChangeCallback');
                if (response.status === 'connected') {
                // Logged into your app and Facebook.
                FB.api('/me?fields=id,first_name,last_name,email', function(result) {
                    document.cookie = "fbdata = " + result.id + "," + result.first_name + "," + result.last_name + "," + result.email;
                    console.log(document.cookie);
                });
            }
        }

And I've accessed it (in any file) using -

我用-访问了它(在任何文件中)

<?php 
    if(isset($_COOKIE['fbdata'])) { 
        echo "welcome ".$_COOKIE['fbdata'];
    }
?>

#7


5  

I was trying to figure this out myself and then realized that the problem is that this is kind of a backwards way of looking at the situation. Rather than trying to pass things from JavaScript to php, maybe it's best to go the other way around, in most cases. PHP code executes on the server and creates the html code (and possibly java script as well). Then the browser loads the page and executes the html and java script.

我试着自己解决这个问题,然后意识到问题是这是一种回顾情况的方式。与其尝试从JavaScript传递到php,不如在大多数情况下,最好是相反的方式。PHP代码在服务器上执行并创建html代码(可能还有java脚本)。然后浏览器加载页面并执行html和java脚本。

It seems like the sensible way to approach situations like this is to use the PHP to create the JavaScript and the html you want and then to use the JavaScript in the page to do whatever PHP can't do. It seems like this would give you the benefits of both PHP and JavaScript in a fairly simple and straight forward way.

处理这种情况的明智方法似乎是使用PHP创建您想要的JavaScript和html,然后在页面中使用JavaScript完成PHP不能完成的任何事情。看起来这将以一种相当简单和直接的方式为您提供PHP和JavaScript的好处。

One thing I've done that gives the appearance of passing things to PHP from your page on the fly is using the html image tag to call on PHP code. Something like this:

我所做的一件事情就是在页面上动态地将东西传递给PHP,那就是使用html图像标记来调用PHP代码。是这样的:

<img src="pic.php">

The PHP code in pic.php would actually create html code before your web page was even loaded, but that html code is basically called upon on the fly. The php code here can be used to create a picture on your page, but it can have any commands you like besides that in it. Maybe it changes the contents of some files on your server, etc. The upside of this is that the php code can be executed from html and I assume JavaScript, but the down side is that the only output it can put on your page is an image. You also have the option of passing variables to the php code through parameters in the url. Page counters will use this technique in many cases.

图片中的PHP代码。php实际上会在加载web页面之前创建html代码,但是html代码基本上是动态调用的。这里的php代码可以用来在页面上创建图片,但是它可以有任何你喜欢的命令,除此之外。它可能会改变服务器上的一些文件的内容,等等。它的好处是php代码可以从html执行,我假设是JavaScript,但是它的缺点是,它只能输出图像。您还可以通过url中的参数向php代码传递变量。页面计数器将在许多情况下使用这种技术。

#8


2  

Is your function, which sets the hidden form value, being called? It is not in this example. You should have no problem modifying a hidden value before posting the form back to the server.

您的函数是否设置了隐藏的表单值?这个例子里没有。在将表单发送回服务器之前,您应该没有任何修改隐藏值的问题。

#9


2  

Here's how I did it (needed to insert a local timezone into php:

我是这样做的(需要在php中插入一个本地时区:

<?php

ob_start();
?>
<script type="text/javascript">

var d = new Date(); 
document.write(d.getTimezoneOffset());     
</script>
<?php

$offset = ob_get_clean();

print_r($offset);

#10


1  

Your code has a few things wrong with it.

您的代码有一些问题。

  • You define a JavaScript function, func_load3(), but do not call it.
  • 定义一个JavaScript函数func_load3(),但不要调用它。
  • 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.
  • 函数定义在错误的位置。当它在您的页面中定义时,它所引用的HTML对象还没有加载。大多数JavaScript代码在执行之前检查文档是否已被完全加载,或者您可以将代码移动到它在页面中引用的元素之上。
  • 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:

可以在表单中的隐藏变量中设置一个JavaScript变量,然后提交它,然后在PHP中读取该值。这里有一个简单的例子可以说明这一点:

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

#11


1  

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

可能您可以使用jquery serialize()方法,这样一切就会一蹴而就。

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

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

//通过这种方式,您还可以在服务器端获得隐藏值。