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

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

You could:

  1. send the information in a form as stated here, (will result in a page refresh)
  2. pass it in ajax (several posts on here about that) (without a page refresh)
  3. make a http request via a XMLHttpRequest request (without a page refresh) like this:

 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楼-- · 2018-12-30 23:38

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.

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.

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:

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

查看更多
浮光初槿花落
4楼-- · 2018-12-30 23:41

Here's how I did it (needed to insert a local timezone into 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);
查看更多
高级女魔头
5楼-- · 2018-12-30 23:42

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.

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.

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

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.

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

查看更多
无与为乐者.
6楼-- · 2018-12-30 23:47

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

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楼-- · 2018-12-30 23:48

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.

查看更多
登录 后发表回答