Can I write PHP inside JavaScript inside PHP?
First of all, it should be noted that this has nothing to do with javascript. You can have any form of text. Your actual question is how to use the variable inside the heredoc.
Heredoc is defined as:
Nowdocs are single quoted strings, what heredocs are for double quoted strings . A nowdoc is set similarly to heredoc, but no parsing is done inside nowdoc. The construct is ideal for embedding PHP code or other large blocks of text without the need for escaping.
This means that since this works:
$name = 'Foo';
echo "My name is $name"; // Using double quotes so variables get expanded
Then this also works:
$name = 'Foo';
echo <<<EOD
My name is <strong>$name</strong>
EOD; // Using heredoc so variables get expanded
This essentially means yes, as long as you put the content 'Do stuff'
into a variable first. Please note that if you are using more complex variables / arrays, it is recommended to do it $array = json_encode($array)
before inserting it into the JS code (imagine if there $name
was one The Boss Wife
), then the apostrophe will destroy your JS, if you do not code it).
source to share
Yes, but I can only get what you want by putting the code after the corresponding HTML. You can echo scripts ... for example this will work:
<div id="footer">Hey</div>
<?php
$myVar = 'Hello';
echo "<SCRIPT>
document.getElementById('footer').innerHTML = '$myVar';
</SCRIPT>";
?> // You will see Hello in the footer
but this won't work:
<?php
$myVar = 'Hello';
echo "<SCRIPT>
document.getElementById('footer').innerHTML = '$myVar';
</SCRIPT>";
?>
<div id="footer">Hey</div>// You will see Hey in the footer
As a side note, these other functions / methods will work as well:
$myVar = 'Hi';
echo "<SCRIPT>
alert('$myVar');
</SCRIPT>";//Alerts 'Hi'
$myVar = 'home.php';
echo "<SCRIPT>
location = '$myVar';
</SCRIPT>";//Takes you to home.php
$myVar = 'hi';
echo "<SCRIPT>
myFunction('$myVar');
</SCRIPT>";//calls myFunction with argument $myVar
source to share