Email
Email

Reputation: 2425

Heredoc escaping PHP variables in JavaScript

I have the following code:

<?php
    if ($zweck == "buchhaltung") {
        echo <<<EOF
        <script type="text/javascript">
            jQuery(document).ready(function() {
            jQuery("#$grid_name").jqGrid({
                url: 'modules/mod_jqgrid/ex_get3.php?tb=$tb'
                .....
        </script>
EOF;
    };
?>

... which does not seem to render properly. Can't we use PHP variables in heredoc in JavaScript code like I use it on the second last line?

On the last line I use " ' " around the PHP variable $tb. Is this syntax correct?

The following code is inside the heredoc as JavaScript code:

dataInit:function(el){
    $(el).datepicker({dateFormat:'dd.mm.yy'});
},
defaultValue: function(){

// Maybe PHP "thinks" that $(el) is a PHP variable?

var currentTime = new Date();

Upvotes: 1

Views: 3203

Answers (2)

Your Common Sense
Your Common Sense

Reputation: 157896

To get you idea:

<?php
    if ($zweck == "buchhaltung"){
?>

<script type="text/javascript">
    jQuery(document).ready(function(){
        jQuery("#<?php echo $grid_name ?>").jqGrid({
            url: 'modules/mod_jqgrid/ex_get3.php?tb=<?php echo $tb?>',...

There isn't any need to escape anything: Just separate your JavaScript code from PHP.

Use each language in its native way.

Upvotes: 1

Jon
Jon

Reputation: 437386

Variable expansion is performed in heredoc strings, so that's not the problem. The code you give should work fine; if it does not, maybe something else is amiss? What exactly do you mean "does not render properly"?

Upvotes: 1

Related Questions