Possible Duplicate:
How to pass JS variable to php?
pass a js variable to a php variable
I'm passing a javascript from a script to an html page using document.getElementById.innerHTML
. The value is printed out correctly in my html page...Now I would know it is possible take this value print in html page and (always in the same page) put it in a php variable?
Create a hidden variable like this
<form method="post">
<input type="hidden" name="hiddenField" id="hiddenField"/>
</form>
in Javascript set value for that variable
document.getElementById("hiddenField").value=6;
in PHP
$value=$_POST['hiddenField'];
If you want to call back to a PHP script from your page, you'll have to look into XMLHttpRequest (or a wrapper library such as jQuery).
After you see a page, the php script finished, so you can only send a var via Ajax to your php file and run the script again.
one easy way to use ajax is jquery
I can think of two ways to do this:
Use an XMLHttpRequest object to send an asynchronous request to some PHP page which records this value.
On the php [holdvalue.php] side:
<?php
$myval = $_GET['sentval'];
// Do something with $myval
?>
On the JavaScript side:
var x = 34; //Some interesting value
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "holdvalue.php/?sentval=" + x, true);
xmlhttp.send();
OR, Use a hidden form field. On the HTML side:
<form id="sendform" method="get" action="holdvalue.php">
<input type="hidden" id="sentval" />
<input type="submit" />
</form>
And on the JS side: document.getElementById("sentval").value = x; // Either the following or send it whenever the user submits the form: document.getElementById("sendform").submit();