0

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
Kashyap Kotak
  • 1,888
  • 2
  • 19
  • 38
  • 1
    you would need quotes around the string otherwise javascript will throw an error. What is the actual question though? btw ` – Professor Abronsius Jun 24 '18 at 07:57
  • If you complain about the missing quotes, just use `echo json_encode($_SESSION['name'])` – Philipp Jun 24 '18 at 07:58
  • Why are you using JavaScript if you just want to put the value of `$_SESSION['name'];` in the `
    `?
    – Mr Glass Jun 24 '18 at 08:04
  • 1
    The expected output is never going to happen. Why the javascript?? – Professor Abronsius Jun 24 '18 at 08:05
  • @RamRaider, Philipp to clear doubts your doubts, please see the edited question. I have added the expected and observed output. – Kashyap Kotak Jun 24 '18 at 08:05
  • @Mr Glass, yes, the values of $_SESSION['name'] just for example is "SomeName" here – Kashyap Kotak Jun 24 '18 at 08:05
  • @KashyapKotak looking at your expected output, it seems you are forcefully bringing JavaScript in between. JavaScript is not required here – dhaker Jun 24 '18 at 08:13
  • @dhaker I want to post-process the myName varriable and derive another value from it and use it later. – Kashyap Kotak Jun 24 '18 at 08:15
  • @KashyapKotak You should mention post-process thing in question then. – dhaker Jun 24 '18 at 08:16
  • Change "scrpit" in your question to "script" – Jeroen Heier Jun 24 '18 at 08:17
  • edited the question for suggestions from @dhaker,Jeroen Heier. Now I have made everything very clear. so whoever have voted it to close, please review and retract the flag. – Kashyap Kotak Jun 24 '18 at 08:20
  • After all, this question is a duplicate - even if you say, it's not... – Philipp Jun 24 '18 at 08:42
  • Possible duplicate of [How to pass variables and data from PHP to JavaScript?](https://stackoverflow.com/questions/23740548/how-to-pass-variables-and-data-from-php-to-javascript) – Philipp Jun 24 '18 at 08:43
  • Did you get your answer ? Otherwise I will give a solution . – PHP Web Jun 24 '18 at 09:03
  • @Philipp please read the last note of my question. The answer to the duplicate question is already present in my question. My problem is different. If I say its not a duplicate, you must look at both the questions carefully and find out why its not a duplicate instead of just believing that its simply a duplicate. – Kashyap Kotak Jun 24 '18 at 12:37
  • Thanks @PHPWeb, I got my answer. – Kashyap Kotak Jun 24 '18 at 12:37
  • It was not needed actually to call the session in JS , without that also you can echo the variable through JS . – PHP Web Jun 24 '18 at 12:58
  • As discussed on another thread, this question is not clear. In the penultimate para it says "I need to get the php value in JS variable" and then in the postscript it says "I am not asking how to get a PHP variable into JS variable". I would urge you to promptly clarify what you want, by editing this post. I'm pleased the accepted answer worked for you, but it has a script tag in the output, and your question does not indicate that's an acceptable outcome. – halfer Jun 24 '18 at 17:57
  • @KashyapKotak compare the answers of the linked thread and the one you got. The answer contains every information, you got in this thread - and even more – Philipp Jun 25 '18 at 08:14
  • @KashyapKotak: please repair this question as per my remarks above. As far as I can tell the requirements are contradictory, and it is a wonder that someone understood it. This question perhaps still ought to be closed. For now, I will downvote, and will un-downvote if you repair. – halfer Jul 13 '18 at 20:00

4 Answers4

1

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.

geco17
  • 5,152
  • 3
  • 21
  • 38
  • what you say as expected output was actually expected but is not the actual. It actually also prints whole "var myName=SomeName".. along with the "var myName" on HTML page. – Kashyap Kotak Jun 24 '18 at 08:17
  • Your question changed during my edit. One way or another you need to store the value of the name session attribute. You can then echo it as needed wherever you like in the HTML, provided it is properly quoted and escaped if you're assigning it to a JavaScript variable. – geco17 Jun 24 '18 at 08:29
1

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>
halfer
  • 19,824
  • 17
  • 99
  • 186
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46
1
<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>
dhaker
  • 1,605
  • 18
  • 19
0

Why not just use this?

<div id="myName">
   <?php
   if(isset($_SESSION['name']) && $_SESSION['name'] != ''){
       echo $_SESSION['name'];
   }
   else
       echo "NotSet";
   ?>;
</div>
Mr Glass
  • 1,186
  • 1
  • 6
  • 14
  • I want to use the js variable for some further logic. – Kashyap Kotak Jun 24 '18 at 08:10
  • Then you need to echo it twice - once inside the ` – Mr Glass Jun 24 '18 at 08:12