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.

1
  • 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. Commented Oct 7, 2014 at 12:12

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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...

Comments

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

Comments

-1
<?php

if ($_SESSION['myVar']==2)
      { 
?>
<script type="text/javascript" >
      document.getElementById("element1").style.visibility = "hidden";
         document.getElementById("element2").style.visibility = "hidden";
</script>
<?php } ?>

1 Comment

This is not answering the question of @the4thDimension.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.