PHP in JavaScript

Hi all,
this produces some inspection notes:

var x = {
  x: 5,
<? echo $aDynamicKey; ?>: ''
};


Should I refactor the code if I'd like to have this kind of declaration? Should I avoid anything like this in general (PHP in JavaScript)? Or can this be regarded as a bug in PHPStorm? I'm not an expert yet. That's why I'm asking.

If I need to refactore this how should it look like?

Thanks,
Robert

5 comments
Comment actions Permalink

Should you avoid putting PHP in JavaScript? in my experience, yes. Do I always avoid it? No. There are a few cases where I've had to do this, nothing seeing any other way (usually it's REALLY complicated JS that calls for it.)

In the case of your code, it depends on how you are using the code below. 95% of my JavaScript is called from HTML and we write all of our HTML from PHP, so we would do this:

<script>
function myfunc(aDynamicKey){

var x = {
    x: 5,
    aDynamicKey: ''
};


}
</script>

echo '<input type="button" id="myfunc('<?=$aDynamicKey?>')" onclick="myfunc">;


Much more portable and easier to find defects, in my opinion. Your mileage will vary. :)

0
Comment actions Permalink

Thank you.
I think I understand.

At least you approach does not bring PHPStorm into troubles.

Anyhow, this

echo '<input type="button" id="mybutton('<?=$aDynamicKey?>')" onclick="myfunc">;


should be


<input type="button" id="mybutton" onclick="myfunc(<?=$aDynamicKey?>)">

Right?

0
Comment actions Permalink

Sorry, yes, "myfunc()"

However, as far as the quotes, depends on if $aDynamicKey is a string or a number.

0
Comment actions Permalink

We don't use PHP to write our HTML. We've one of those rare shops that write HTML/JS/CSS and just use PHP for database.

But I do use PHP vars to determine which options to use for certain javascript features, like Datatables:

$('#datatable').dataTable({
     <?php if ($tSize > 20) {?>
        "bFilter":true,
     <?php }?>
        "sPaginationType": "full_numbers",
        "bAutoWidth":true,
        "bStateSave":true,
        "iCookieDuration" : 60*60*24
    });

This does throw an IDE warning. But is fine to run. We just ignore the warnings. Keep in mind though; inside JS, we ONLY use PHP to determine options. Not to write the JS. bascially we use PHP for "templating".

0

Please sign in to leave a comment.