Reputation: 3885
I wonder what's the best method for writing javascript code into a PHP variable?
Some times it might be quite long javascript code... Is there a way without escaping all quotes?
<?php
echo '
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
a_div.innerHTML = '<iframe style="width:100%;height:300px;" id="iframe_upload" src="index.php">';
</script>'
?>
Upvotes: 0
Views: 630
Reputation: 29208
Use heredoc. For example:
$var = EOF<<<
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
a_div.innerHTML = '<iframe style="width:100%;height:300px;" id="iframe_upload" src="index.php">';
</script>
EOF;
The EOF
can be any arbitrary string you want, it just has to come directly after the <<<
delimiter and match on both sides of the string you want to create.
Upvotes: 3
Reputation: 140210
Just do:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
a_div.innerHTML = '<iframe style="width:100%;height:300px;" id="iframe_upload" src="index.php">';
</script>
And in case you need php in there somewhere:
a_div.innerHTML = '<iframe style="width:<?php echo $width; ?>;height:300px;" id="iframe_upload" src="index.php">';
Upvotes: 1
Reputation: 318468
The answer is simple don't mix PHP code and HTML/JavaScript and if you need to do so, end the PHP block with ?>
and open it again with <?php
after your HTML/JS block.
If you need it inside a variable, you could either use output buffering which is kind of messy though or use Heredoc/Nowdoc strings:
<?php
$foo = <<<FOOBAR
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
a_div.innerHTML = '<iframe style="width:100%;height:300px;" id="iframe_upload" src="index.php">';
</script>
FOOBAR;
?>
Upvotes: 1