tags:

views:

268

answers:

4

is there a way to disable javascript codes in a particular page using certain php codes? I need to ensure that all the javascripts used in a page should not give any result (even errors) when run.

A: 

There is no such way because PHP run on your server and JavaScript runs client-side once your server has done it's part and it's done by browser.

What you can do is make sure that your JS doesn't have errors or remove all the JavaScript.

RaYell
<a href="#1673710">cballou</a>s answer is correct but it is a pain if you have a javascript riddled through out your code.
Matt Smith
A: 

You could throw PHP conditionals around the Javascript so they won't display on your page:

<script type="text/javascript">
<?php if($showJavascript): ?>
// executes the following function
myJavascriptFunc();
<?php endif; ?>

function myJavascriptFunc() {

}
</script>

And to resolve any issues from my comments:

<?php var showJavascript = <?php echo ($showJavascript) ? 'true' : 'false'; ?>;
<script type="text/javascript" src="myFile.js"></script>

In the last case you should check the boolean value of showJavascript in myFile.js.

cballou
This won't work for external JS files included with `<script type="text/javascript" src="myscript.js"></script>`
RaYell
However it would work if you throw the conditional around the entire <script> declaration block as a whole. You also have the capability of setting a global variable prior to including myscript.js and having the file check for that variable.
cballou
+2  A: 

Why don't you just not send the javascript down for those particular pages?

David Archer
A: 

The easiest way (and the dirtiest, slowest, etc) is to turn on the output buffer at the start of the page, and, before echoing the buffer's content at the end, remove all traces of javascript, either through regular expressions, a html parser, or a combination of both.

<?php
    ob_start();

    // your code here

    $output = ob_get_contents();
    ob_end_clean();

    // Purge your $output here, remove all <script> tags, onclick events, etc.

    echo $output;
?>

How to purge the output has already been answered on SO many, many times.

Duroth