1

Possible Duplicate:
How to pass JavaScript variables to PHP?

How to assign on this php variable assign javasript value

<script type="text/javascript">

var var_example = "2222";

</script>

<?php 
  echo $var_example_php =   ?        

  /// How to assign on this php variable asign javasript value 
?>
Waldi
  • 39,242
  • 6
  • 30
  • 78
Chirag
  • 61
  • 1
  • 1
  • 4
  • 4
    There has been 100 of questions exactly dealing with same question on SO – Prashant Singh Oct 27 '12 at 05:45
  • You commented that you want to assing PHP value to javascript, but your example shows that you are assigning javascript variable value to php – Mr. Alien Oct 27 '12 at 05:47
  • you can do it with `ob_start()` function.. check out my answer – Mihai Matei Oct 27 '12 at 06:27
  • Of course there are ways to do that, but they are not simple/elegant. – Mikey Jan 29 '17 at 08:38
  • (Stupid rule the one with editing your post only 5 mins !) JS to PHP: Use hidden input in PHP, set valute in JS, submit page. Not elegant, though. But if you really need to do that... PHP to JS: it is currrently done in scripts. – Mikey Jan 29 '17 at 08:47

4 Answers4

10

You simply cannot do that, you need to understand the difference between client/server side programming, you cannot assign Javascript value to PHP variable, yea but you can assign PHP value to your javascript

Mr. Alien
  • 153,751
  • 34
  • 298
  • 278
8

You cannot do that. An alternative may be creating a cookie using javascript and then read the cookie in PHP.

In Javascript:

<script type="text/javascript">
    document.cookie = "cookieName=cookieValue";
</script>

And in PHP

<?php 
   $phpVar =  $_COOKIE['cookieName'];

   echo $phpVar;
?>

But an important point, for this to run the browser needs reload.

Best regards...

avolquez
  • 753
  • 1
  • 7
  • 20
  • Surely this has really worked for me, I knew I could use cookies as an alternative BUT was worried of adding plugins. And this did not require that. – mukamaivan Jan 15 '13 at 22:01
0

You can do it using ob_start() function (documentation). If you use this method you can call a function and parse the html content. You search for your variable and get it with php..

<html>
  <head>
  <?php
    $my_var = '';


    function callback($buffer)
    {
      global $my_var;
      $arr = array();

      preg_match('/var_example = \"(?P<var>\w+)\"*/', $arr, $buffer);

      $my_var = $arr['var'][0];  

      return $buffer;
    }

    ob_start("callback");

  ?>
  <script type="text/javascript">

    var var_example = "2222";

  </script>
  <?php

    ob_end_flush();

  ?>
  </head>
  <body>
  </body>
</html>
Mihai Matei
  • 24,166
  • 5
  • 32
  • 50
-2

Please try this:

Use document.write function in javascript.

<?php
     $var_example_php = "<script>document.write(var_example);</script>";
     echo $var_example_php;
?>
suresh gopal
  • 3,138
  • 6
  • 27
  • 58