-3

can javascript or jquery variable can be read by php code?

Example

<script>
   var num = 3;
</script>
<php?
   $a = 20;
   $b = num*$a;
?>

anyone?

Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
Jerrime25
  • 13
  • 1
  • 8
  • 2
    somany people http://goo.gl/XfFnC6 – ɹɐqʞɐ zoɹǝɟ Jul 01 '14 at 04:05
  • PHP - server side language; JS - client side language. What do you think? – Derek 朕會功夫 Jul 01 '14 at 04:06
  • If you want to process a variable on server, consider using node.js. Other than that, you are out of luck. You can not directly access client side variables on server without a POST(or whatever!) request. Considering the information you give in your question, `$_POST` is your answer. – Fr0zenFyr Jul 01 '14 at 04:14
  • possible duplicate of [How to pass variables and data from PHP to JavaScript?](http://stackoverflow.com/questions/23740548/how-to-pass-variables-and-data-from-php-to-javascript) – nobody Jul 01 '14 at 04:24

2 Answers2

2

PHP is interpreted on the server. Javascript is interpreted in the browser. Since PHP cannot run after the HTTP request has been fulfilled and a response has been sent to the browser, it is not possible for PHP to access a javascript variable.

Sarcastron
  • 1,527
  • 14
  • 20
  • I don't agree, this is not a complete answer. client side variables can be accessed on server if they are sent with a `$_POST` request. – Fr0zenFyr Jul 01 '14 at 04:16
  • 1
    @Fr0zenFyr - The data is copied and sent to the server. The server can process the data, but the server can never access client-side variables. – Derek 朕會功夫 Jul 01 '14 at 04:41
0

Short answer - No it can't. But there is an alternative known as AJAX where you can send a javascript variable to a php page and make it accessible to that page. Consider the following example:

$.ajax({
   url:'some-php-page.php',
   type:'post',
   data:{num:3},
   success:function(data_returned)
   {
      // do anything you want with the data returned back
      alert(data_returned); // will alert 60
   }
});

some-php-page.php

$num = $_POST['num']; // the key used in the "data" attribute of the ajax call
$a = 20;
$b = $num*$a;
echo $b;

Of course you'll need to include jQuery library in order to use the $.ajax({}). This can be done through plain javascript too, but I prefer to use jQuery as it is much simpler.

asprin
  • 9,579
  • 12
  • 66
  • 119