0
     <?php
         //Started or resumed the session
     ?>
     <html>
        <head>
           <script type="text/javascript" src="myjavascript.js"></script>
        </head>

        <body>
            <div class="myClass" data-attr=<?php echo $_SESSION["mySession"]?>></div>
        </body>
     </html>

This is my php.

In my js File, I have something like

   $(function(){
        alert($(".myClass").attr("data-attr"));
    });

It echo the right value. I don't understand the order of execution. Because head section comes first , then my div[myclass]. So evaluation occurs later point of time.

Is it echoes because of that I surround the code inside domready. Is it the reason? Will it work always?

Gibbs
  • 21,904
  • 13
  • 74
  • 138

3 Answers3

3

PHP is ran on the server before any JavaScript is ran. So first the PHP is executed, then the JavaScript is executed afterwards. Next the $(function(){ ... }); means to run the JavaScript once the DOM is finished loading, so alert($(".myClass").attr("data-attr")); only happens after the DOM loads, which is why it will work properly.

Spencer Wieczorek
  • 21,229
  • 7
  • 44
  • 54
1

PHP is executed and rendered by the server which receives your request. Javascript is executed by the browser after receiving the contennt

 <?php
     //Started or resumed the session
     //Not visible to the browser
echo "Something";
 ?>
 <html>
    <head>
       <script type="text/javascript" src="myjavascript.js"></script>
    </head>

    <body>
        <div class="myClass" data-attr=<?php echo $_SESSION["mySession"]?>></div>
    </body>
 </html>

This is parsed and the browser receives content similar to:

something
 <html>
    <head>
       <script type="text/javascript" src="myjavascript.js"></script>
    </head>

    <body>
        <div class="myClass" data-attr="whateverisinthesession"></div>
    </body>
 </html>

After this, it will execute the javascript.

TL;DR: First php is executed, then javascript

SoWhat
  • 5,564
  • 2
  • 28
  • 59
0

It will work correctly! but only beacause you surrounded your JS code with $(function()){} (shorthand to $( document ).ready()) otherwise, the browser may try to execute your JS code first, even before the page completly load. Keep in mind that PHP will always execute before, when your browser loads an HTML page, the PHP was already executed in server-side

Adriel Santos
  • 653
  • 7
  • 15