I have the following code in JavaScript:
<script>
var a="Hello";
</script>
PHP Code:-
<?php
$variable = // I want the above JavaScript variable 'a' value to be stored here
?>
Note : I don't want it in a form submission. I have some logic in JavaScript and I want to use it in the same PHP page... Please let me know how I can do this.
Javascript will be interpreted in Client's browser and you can not assign it to PHP variable which is interpreted on SERVER .
php $var1 = $_POST['var1']; $var2 = $_POST['var2']; $getvalue="SELECT id,name from table1 WHERE column1='$var1' and column2='$var2'"; $result=mysql_query($getvalue) or die(mysql_error()); while($row=mysql_fetch_array($result)){ extract($row); echo $name; } ?>
You can easily get the JavaScript variable value on the same page in PHP. Try the following codeL. <script> var res = "success"; </script> <? php echo "<script>document.
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
to be created as string 'foo'$a
to be outputted in context of some JavaScript (which is not currently executing)$a
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.
<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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With