Page 1 of 1

Execute JavaScript/DOM before PHP

Posted: Mon Aug 25, 2008 5:10 am
by Bughy
I have this function:

Code: Select all

 
<head>
<script type="text/javascript">
function change(){
    var x = document.getElementById("myCode");
    var y = x.innerHTML;
    y= y.replace(/</g, "<")
    y= y.replace(/>/g,">")
    document.getElementById('myCode').innerHTML = y;
}
</script>
</head>
<body onload="change();">
 
<div id="myCode">
<?php echo 'Batman'; ?>
</div>
 
</body>
 
If I write simple HTML code in myCode div, works perfect, but when I write PHP code, it gets executed, and there's nothing to replace anymore.

If you haven't already figured out, I want to replace the "<" and the ">", so the code is being displayed, not executed.
Any suggestions?

Re: Execute JavaScript/DOM before PHP

Posted: Mon Aug 25, 2008 6:08 am
by matthijs
PHP is always executed first. So you'll have to do the conversion server side. Maybe with some preg_replace or htmlentities

Code: Select all

 
echo htmlentities('<?php echo \'Batman\'; ?>'); // produces <?php echo 'Batman'; ?>
 
edit: the comment view here removed the slashes \ I put in front of the ' surrounding Batman.

Re: Execute JavaScript/DOM before PHP

Posted: Mon Aug 25, 2008 6:12 am
by Bughy
uhm, not good, it shouldn't request any other writing besides the actual code.

Re: Execute JavaScript/DOM before PHP

Posted: Mon Aug 25, 2008 6:21 am
by matthijs
I don't understand what you want to do then. Maybe you could explain that.

Re: Execute JavaScript/DOM before PHP

Posted: Mon Aug 25, 2008 6:31 am
by Bughy
i want to rewrite myCode div, all that's written in it

Re: Execute JavaScript/DOM before PHP

Posted: Mon Aug 25, 2008 6:49 am
by matthijs