skip to Main Content

I’d like to dynamically assign a JS variable from one of my php page-templates in order to use the assigned variable within my bundle.js file.

I’m doing this using this way:

template-some-page.php:

<?php
       echo "<script>
       var javascriptVar = 'success';
       </script>";
?>

<div>
  ...
</div>

bundle.js:

function readVar() {
   console.log(javascriptVar )
}

This approach works perfectly fine, but the question is it a good practice using this way?
Is creating a tag within the body is safe ?

enter image description here

2

Answers


  1. <?php
    $script = "
     <script>
      console.log("Hello World");
      var javascriptVar = "success";   
     </script>";
    echo $script; 
    ?>
    

    (or)

    you can close the PHP tag and write some Html or js script and re-open the PHP tag to continue writing the remaining PHP code in the same .php extension file

    <?php 
     // my PHP code
    ?>
    <script>
      console.log("Hello World");
      var javascriptVar = "success";   
    </script>
    <?php 
     // my PHP code
    ?>
    
    Login or Signup to reply.
  2. The code you have shown presents no security issue save one: it stuffs your javascriptVar into the global Javascript object.

    You might do better to use this.

        echo "<script>
           var annasApp = annasApp || {};
           annasApp.javascriptVar = 'success';
           </script>";
    

    The line var annasApp = annasApp || {}; creates an object in the global namespace if it doesn’t already exist. Then it assigns a property value to the object. This makes for a cleaner and less error-prone global namespace — other code is less likely to step on your code and vice versa.

    If your code wants to do annasApp.javascriptVar = $phpVariable; you do have a potential security problem. You must escape the data in $phpVariable before echoing it. If you don’t, your code might be vulnerable to cross-site scripting attacks. A good and safe way to handle that is using JSON.

        $jsonVariable = json_encode( htmlspecialchars( $phpVariable ) );
        echo "<script>
           var annasApp = annasApp || {};
           annasApp.javascriptVar = $jsonVariable;
           </script>";
    

    htmlspecialchars() is unnecessary unless your Javascript data will be rendered using HTML.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search