Ben
Ben

Reputation: 25827

How to incorporate a PHP-generated value into JavaScript code on the page?

I've tried this, but it’s not working:

<?php  
  $htmlString= 'testing';
?>
<html>
  <body>
    <script type="text/javascript">  
      var htmlString=<?php echo $htmlString; ?>;
      alert(htmlString);
    </script>
  </body>
</html>

Upvotes: 41

Views: 258558

Answers (6)

inf3rno
inf3rno

Reputation: 26157

The only proper way to put server side data into generated JavaScript code:

<?php $jsString = '"; alert("xss"); //'; ?>
<html>
  <body>
    <script type="text/javascript">      
      var jsStringFromPhp=<?php echo json_encode($jsString); ?>;
      alert(jsStringFromPhp);
    </script>
  </body>
</html>

With simple quotes the content of your variable is not escaped against HTML and JavaScript, so it is vulnerable by XSS attacks...

For similar reasons I recommend to use document.createTextNode() instead of setting the innerHTML. Of course it is slower, but more secure...

Upvotes: 14

2winners
2winners

Reputation: 1

if you have a lot of information to transfer sometimes its just easyer to echo the entire text like below:

<?php echo "  
const JData = ".$Jfile.";
const Page = JData['Page'][".$key."];
";?>

here i transfered JSON data into JS that i can recall in the javascript later and only have 1 place i inject the php info all 1500 lines of java below only call upon the JData constant makes for a clean work space

echo"
    <script defer> 
    let LP1 = '$LP1';
    let LP2 = '$LP2';
    setTimeout(openadmin(),500);
    function openadmin(){
        console.log(document.getElementById(LP1));
        document.getElementById(LP1).classList.add('show');
        document.getElementById(LP2).scrollIntoView();
    }
    
    </script>
";

this is used to go back to where was lasted clicked submit form this is inside a php document

$k = 0;
foreach ($newgalist as $xx => $val) {
   $px = $MID[$k];
   echo "
                        
   var object = scene.getObjectByName('$px');
   var L1 = scene.getObjectByName('spotR$px');
   var L2 = scene.getObjectByName('spotL$px');
   var T1 = scene.getObjectByName('Title$px');
   var T2 = scene.getObjectByName('Quote$px');
   var TL = scene.getObjectByName('target$px');

   var xpos = ".$val['offset']['x']."
   object.position.x = xpos;
   L1.position.x = xpos;
   L2.position.x = xpos+10;
   T1.position.x = xpos-10;
   T2.position.x = xpos;
   TL.position.x = xpos;
  //document.getObjectByName('InfoOverlay$px')
                        
  ";
  $k++;
}

but its quite ugly like this ( this was usefull for fast prototying this code no longer exists in my final code because its ugly)

but in the end the PHP "string" writes as : string if you need to string it into js either php include the tags "\"string\"" or have the tags prewriten function('$String') for function('string') also works in html like value="<?php echo $String;?>" tho make sure there are no spaces between the " and < because they will show up sometimes if you write the entire piece in a echo you can get away with echo" function ($data){}"; or echo" <input input\"text\" value=\"latest number is:$number\"></input>"; but if you call from a array you need to echo" function(".$data[0]."){}"; or echo"<input input\"text\" value=\"latest number is:".$numbers[$i]."\"></input>"; close the string add the php data then open the string again this method of complete writing in php the html or js can be usefull if you page is not set in stone and need to create new content based on prior inputs

Upvotes: -1

Daren Thomas
Daren Thomas

Reputation: 70354

Community warning: the suggested solution is not safe, being prone to XSS attack. Consider using json_encode() as suggested in the answer below

Try this:

<?php $htmlString= 'testing'; ?>
<html>
  <body>
    <script type="text/javascript">  
      // notice the quotes around the ?php tag         
      var htmlString="<?php echo $htmlString; ?>";
      alert(htmlString);
    </script>
  </body>
</html>

When you run into problems like this one, a good idea is to check your browser for JavaScript errors. Different browsers have different ways of showing this, but look for a javascript console or something like that. Also, check the source of your page as viewed by the browser.

Sometimes beginners are confused about the quotes in the string: In the PHP part, you assigned 'testing' to $htmlString. This puts a string value inside that variable, but the value does not have the quotes in it: They are just for the interpreter, so he knows: oh, now comes a string literal.

Upvotes: 65

JLavoie
JLavoie

Reputation: 17626

All the explanations above doesn't work if you work with .js files. If you want to parse PHP into .js files, you have to make changes on your server by modfiying the .htaccess in which the .js files reside using the following commands:

<FilesMatch "\.(js)$">
    AddHandler application/x-httpd-php .js
</FilesMatch>

Then, a file test.js files containing the following code will execute .JS on client side with the parsed PHP on server-side:

<html>
<head>
<script>
function myFunction(){
   alert("Hello World!");
}
</script>
</head>
<body>
<button onclick="myFunction()"><?php echo "My button";?></button>
</body>
</html>

Upvotes: 11

second
second

Reputation: 28665

you need quotes around the string in javascript

var htmlString="<?php echo $htmlString; ?>";

Upvotes: 6

John Conde
John Conde

Reputation: 219934

You're missing quotes around your string:

...
var htmlString="<?php echo $htmlString; ?>";
...

Upvotes: 30

Related Questions