document.getElement...">

Can I write PHP inside JavaScript inside PHP?

Inside PHP script I have this:

echo <<<EOD

<script type="text/javascript">
document.getElementById('my_element_id').innerHTML='Do stuff';
</script>

EOD;

      

Can PHP be added to JavaScript? Replace the "Do things" part with PHP code? If so, how should I do this?

+3


source to share


3 answers


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).

DEMO

+3


source


Can be done as:

<?php 
$anyphpvariable='foo';
echo <<<EOD 
    <script type="text/javascript">
       document.getElementById('my_element_id').innerHTML=$anyphpvariable;

    </script>
EOD;
?>

      



Any of the php can be assigned to JS and its good practice. But not JS can assign anything to PHP.

0


source


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

      

-2


source







All Articles