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>
Here is the Working example: Get javascript variable value on the same page in php.
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.
Your code has a few things wrong with it.
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:
May be you could use jquery serialize() method so that everything will be at one go.
//this way you could get the hidden value as well in the server side.
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.
just save it in a cookie:
and then read it with php
its not a pretty solution, but it works. Cheers.