How can I store JavaScript variable output into a PHP variable?
The ideal method would be to pass it with an AJAX call, but for a quick and dirty method, all you'd have to do is reload the page with this variable in a $_GET
parameter -
<script>
var a="Hello";
window.location.href = window.location.href+'?a='+a;
</script>
Your page will reload and now in your PHP, you'll have access to the $_GET['a']
variable.
<?php
$variable = $_GET['a'];
?>
<html>
<head>
<script>
var a="Hello";
</script>
</head>
<body>
<?php
echo $variable = "<script>document.write(a)</script>"; //I want above javascript variable 'a' value to be store here
?>
</body>
You have to remember that if JS and PHP live in the same document, the PHP will be executed first (at the server) and the JS will be executed second (at the browser)--and the two will NEVER interact (excepting where you output JS with PHP, which is not really an interaction between the two engines).
With that in mind, the closest you could come is to use a PHP variable in your JS:
<?php
$a = 'foo'; // $a now holds PHP string foo
?>
<script>
var a = '<?php echo $a; ?>'; //outputting string foo in context of JS
//must wrap in quotes so that it is still string foo when JS does execute
//when this DOES execute in the browser, PHP will have already completed all processing and exited
</script>
<?php
//do something else with $a
//JS still hasn't executed at this point
?>
As I stated, in this scenario the PHP (ALL of it) executes FIRST at the server, causing:
- a PHP variable
$a
to be created as string 'foo' - the value of
$a
to be outputted in context of some JavaScript (which is not currently executing) - more done with PHP's
$a
- all output, including the JS with the var assignment, is sent to the browser.
As written, this results in the following being sent to the browser for execution (I removed the JS comments for clarity):
<script>
var a = 'foo';
</script>
Then, and only then, will the JS start executing with its own variable a
set to "foo" (at which point PHP is out of the picture).
In other words, if the two live in the same document and no extra interaction with the server is performed, JS can NOT cause any effect in PHP. Furthermore, PHP is limited in its effect on JS to the simple ability to output some JS or something in context of JS.