SnarkyDTheman
SnarkyDTheman

Reputation: 265

PHP: Code gets turned into HTML <!-- Comments? -->

when I enter in code like this:

<p>Hello <? echo $name; ?>, How are you?</p>

It prints:

<p>Hello <!--? echo $name; ?-->, How are you?</p>

As a comment. I have it in a file called base.js with this code:

function showName() {
   document.getElementById("name").innerHTML = "<p>Hello <? echo $name; ?>, How are you?</p>";
}

So I embed the .js file like so:

<script type="text/javascript" src="base.js"></script>

So, after it changes the <p id="name"></p> I get:

<p id="name">Hello <!--? echo $name; ?-->, How are you?</p>

I had the code in the .php file, and it seemed to work fine. Now that I have it in a separate base.js file, it ceases to function. Help!

Upvotes: 5

Views: 7646

Answers (4)

parisa parvizi
parisa parvizi

Reputation: 1

speaking from 2021 :

1- you can use js and php.

2- CDATA is deprecated.

Upvotes: 0

mplungjan
mplungjan

Reputation: 177692

That is because it is no longer php.

Change to

<script type="text/javascript" src="base.php"></script>

and have a 
<?php header("content-type:text/javascript"); 
$name = "...";
?>

function showName() {
   document.getElementById("name").innerHTML = "<p>Hello <?php echo $name; ?>, How are you?</p>";
}

Or

change to

function showName(name) {
   document.getElementById("name").innerHTML = "<p>Hello "+name+", How are you?</p>";
}

and in the php file have

<script>
// using json_encode to make the string safe for script injection. 
// Still needs quotes for a single string
showName("<?php echo json_encode($name); ?>");
</script>

Upvotes: 6

Anthony
Anthony

Reputation: 3218

Thist of all you cannot run php in the JS. The second is you have to do smth like this to avoid problem with comments:

//<![CDATA[
    function showName() {
       document.getElementById("name").innerHTML = "<p>Hello <? echo $name; ?>, How are you?</p>";
    }
//]]>

Upvotes: 0

fivedigit
fivedigit

Reputation: 18672

PHP is processed on the server side, not client side. You cannot execute PHP code on the client side.

Upvotes: 0

Related Questions