0

I have embedded some javascript within php code. This was necessary after checking some php session variable value, and upon result, I use some JS within php to decide if some elements will be shown or not. Here is an example:

<?php

if ($_SESSION['myVar']==2)
      { echo '<script type="text/javascript" >

          document.getElementById("element1").style.visibility = "hidden";
         document.getElementById("element2").style.visibility = "hidden";

            </script>';
?>

The code works perfect for me. My question is : is the JS executed at the webserver(since it is embedded within php code) , initializing the page before it is sent to the client browser (and that what I think), or does the php portion run at the server, and the JS runs at the client later??

I know in normal situations the JS runs at the client browser,but was suspicious in this case,

I'm a junior programmer and any help is appreciated, thanks in advance.

  • 2
    never combine server-side and client-side scripting. I have worst experiences doing so. If you really want to use PHP in clientside validations, Use AJAX calls and get JSON from PHP to use in javascript. –  Oct 07 '14 at 12:12

4 Answers4

1

Javascript is always executed in the browser of the client. The php code just inserts the javascript code as a block of text and the browser reads it as code.

Jerodev
  • 32,252
  • 11
  • 87
  • 108
1

JavaScript is executed on client-side no matter what, but your PHP code you just inserted the code to make it available for the browser to execute it...

Asher
  • 557
  • 3
  • 18
1

Php sends the JavaScript back to the Client as a response and then on the Client side JavaScript is run. Please read this ANSWER 123 and you might have a better explanation >> PHP & Embedded JavaScript Behavior. Thanks

Community
  • 1
  • 1
Meer
  • 1,006
  • 10
  • 15
-1
<?php

if ($_SESSION['myVar']==2)
      { 
?>
<script type="text/javascript" >
      document.getElementById("element1").style.visibility = "hidden";
         document.getElementById("element2").style.visibility = "hidden";
</script>
<?php } ?>
Lundin
  • 195,001
  • 40
  • 254
  • 396
shashik493
  • 790
  • 1
  • 10
  • 12