2

I am facing issue regarding passing javascript variables to php within same function. My code looks like this

 else if(msg_type[i] == 'code' ){
    var code_action = 'test';
    <?php
    function foobar_func(){
    return "<script>document.writeln(action[i]);</script>";
    }
    add_shortcode( 'foobar', 'foobar_func' );
    ?>

}

what i am doing is passing that code_action variable of javascript and returning it to function without using ajax or jquery...is there any possible method to do so...??

any possibilities will be appreciated. Thank you

Sandesh Satyal
  • 196
  • 1
  • 8
  • you cant pass javascript > php.. the php is run on the server before the javascript is rendered so the javascript has no clue about the php. Youll need ajax or cookies or something like that. – DevDonkey Sep 30 '15 at 08:10
  • Shortly: NO! This is because JS is executed on the client (the browser) and PHP on the server. So without any sort of (HTTP) request (back to the server) it's not possible. – Havelock Sep 30 '15 at 08:10
  • no.. because PHP runs in server where are javascript is executed in client – Arun P Johny Sep 30 '15 at 08:10
  • seems as i need to alter my code to a new approach. – Sandesh Satyal Sep 30 '15 at 09:03

1 Answers1

0

When you make a request to invoke this page, your <?PHP ?> block is executed in the server. It creates a processed output in the web page (in your code) and send it to the browser. Now the browser executes your <script> </script> blocks.

I hope you understand that passing variables from <script></script> to <?PHP ?> is impossible since the latter happened in the past.

But you can use it other way around by trying to pass variables from the PHP to JS.

When you write

<?PHP
   $fromServer = "from php";

   echo "<script> var fromServer = " . $fromServer . " </script>
?>

.. it passes data from your PHP to JS.

You can, however, use HTTP POST or GET method to pass data from JS to PHP to be used in the next session.

Charlie
  • 22,886
  • 11
  • 59
  • 90
  • i am aware of get and post method to send data from js to php but it will be in next session, what i wanted was the job to be done within same session. i.e pass variables directly from js to php. I now know that it might not be possible. – Sandesh Satyal Sep 30 '15 at 09:01
  • any idea about how this code is working ?? – Sandesh Satyal Sep 30 '15 at 09:07
  • "; } ?> – Sandesh Satyal Sep 30 '15 at 09:07
  • What you need to understand is that PHP happens in the past when you look from JS per each page load. – Charlie Sep 30 '15 at 09:57