0

I have a JS variable:

var str = "hello world";

How could I pass this JS variable str to a PHP variable like $str = this JS variable?

echo $str; //output "hello world"
Lewis
  • 14,132
  • 12
  • 66
  • 87
  • 2
    You can't. PHP is executed on the server, by the time the page is in the browser on the users computer and javascript is executing, it's too late to pass stuff directly to the server, you have to load another page, either the one you're on needs to be reloaded again, you redirect to another page, or you use ajax or other techniques that can load a page without the browser refreshing. – adeneo May 17 '14 at 14:38
  • 1
    If you search here you will probably found an answer. This has been asked a gazillion times. – Felix Kling May 17 '14 at 14:40
  • @adeneo: Is this posible if my PHP var is executed before the JS one? – Lewis May 17 '14 at 14:42
  • @FelixKling - Hard to find a good duplicate at least ? – adeneo May 17 '14 at 14:43
  • Also http://stackoverflow.com/questions/1917576/how-to-pass-javascript-variables-to-php?lq=1 – PeeHaa May 17 '14 at 15:06
  • Also http://stackoverflow.com/search?q=%5Bjavascript%5D+%5Bphp%5D++pass+js+variable+to+php – PeeHaa May 17 '14 at 15:07

2 Answers2

0

have you tried this?

  <script type="text/javascript">
           var str = 'hello world';
        </script>
 <?php          
      $roo = " <script type=\"text/javascript\">
          document.write(str) ;
        </script>";

     echo $roo; // will print hello world           
  ?>

EDit:

or use AJAX to get javascript variables .

echo_Me
  • 37,078
  • 5
  • 58
  • 78
0

You could add it to a postback event, and in your php read it from the posted data

using an xhr request you could then also print your output

Icepickle
  • 12,689
  • 3
  • 34
  • 48