简体   繁体   中英

Echoing PHP variable into JavaScript variable prints the PHP variable in HTML

I have a HTML page with a script tag with PHP in it as follows:

<div id="myName">
<script type="text/javascript">
   var myName = <?php
   if(isset($_SESSION['name']) && $_SESSION['name'] != ''){
       echo $_SESSION['name'];
   }
   else
       echo "NotSet";
   ?>;
document.write(myName);
</script>
</div>

But running this actually prints like below:

<div id="myName">
    var myName=SomeName;
    document.write(myName);
</div>

Expected:

<div id="myName">
    SomeName
</div>

On doing inspect element:

<div id="myName">
<script type="text/javascript">
    "var myName=SomeName;
    document.write(myName);"
</script>
</div>

I want to post-process the variable myName and derive other values ahead in JS logic. So, I need to get the php value in JS variable.

Please note: I am not asking how to get a PHP variable into JS variable (for which there are many different questions on Stack Overflow). This is a different question and hence not a duplicate for those questions.

If your code is

<div id="myName">
<scrpit type="text/javascript">
   var myName = <?php
   if(isset($_SESSION['name']) && $_SESSION['name'] != ''){
       echo $_SESSION['name'];
   }
   else
       echo "Not Set";
   ?>;
</script>
</div>

Then the expected result can only be

<div id=" myName">
    <script type="text/javascript">
        var myName = RESULT OF PHP CODE HERE
    </script>
</div>

If you want the expected output as described in your question, change your HTML/php to

<div id="myName">
   <?php
   if(isset($_SESSION['name']) && $_SESSION['name'] != ''){
       echo $_SESSION['name'];
   }
   else
       echo "Not Set";
   ?>;
</div>

EDIT

After posting I saw the comments on another answer. You want to use the variable in two places so you have to store the result of your php logic somewhere if the name session variable doesn't change and/or make a function to get it if it can change.

For one such example

<?php
    function getNameFromSession() {
        if(isset($_SESSION['name']) && $_SESSION['name'] != ''){
            return $_SESSION['name'];
       }
       else
            return "Not Set";
    }

    $myName = getNameFromSession();
?>

<div id=" myName">
    <?php echo $myName; ?>
    <script type="text/javascript">
        var myName = "<?php echo $myName; ?>";
    </script>
</div>

Note that in any case your script would probably be better off in the element.

You could assign the PHP data as a JavaSscript variable like this - it will be available for further client side processing as desired and you can update the DOM to reflect the content using standard methods.

<html>
    <head>
        <title>php & js vars</title>
    </head>
    <body>
    <div id='myName'>
        <script>
            <?php
                printf( 'var myName="%s";', !empty( $_SESSION['name'] ) ? $_SESSION['name'] : 'NotSet' );
            ?>
            document.getElementById('myName').innerHTML=myName;
            alert( myName );// var still available...
        </script>
    </div>
    </body>
</html>

Update

The above snippet was written in haste with little thought given to the various ways in which it could break, but to accommodate for double quotes you could make use of htmlentities

<?php
    session_start();
    $_SESSION['name']='Geronimo"s Revenge';
?>
<html>
    <head>
        <title>php & js vars</title>
    </head>
    <body>
    <div id='myName'>
        <script>
            <?php
                printf( 'var myName="%s";', !empty( $_SESSION['name'] ) ? htmlentities( $_SESSION['name'], ENT_QUOTES   ) : 'NotSet' );
            ?>
            document.getElementById('myName').innerHTML=myName;
        </script>
    </div>
    </body>
</html>
<div id="myName">

</div>

<scrpit type="text/javascript">
   <?php
   if(isset($_SESSION['name']) && $_SESSION['name'] != ''){ ?>
       var myName =<?php echo $_SESSION['name'];?> ;
   <?php }
   else{
  ?>
      var myName = "NotSet";
   <?php } ?>;
  document.getElementById("myName").innerHTML=myName ;

document.write(myName);
</script>

Why not just use this?

<div id="myName">
   <?php
   if(isset($_SESSION['name']) && $_SESSION['name'] != ''){
       echo $_SESSION['name'];
   }
   else
       echo "NotSet";
   ?>;
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM