0

I need to remove some Javascript code based on a server side condition (PHP). What I currently have is a variable holding the Javascript code as text and based on the condition I either echo it or not. However, it's cumbersome to maintain. How do I go about doing it?

I also tried to use something like what follows, but it's not working.

<?php if(condition) { ?> <script> stuff here </script> <?php } ?>

I'm sorry for the formatting, I have no idea why the less-then sign is making the entire line disappear.

6
  • That approach should work OK. But there are two other errors in that line: no ? before php and no $ before condition. If it's just formatting - fix it, but if it's in your coe - that is a source of the problem Commented Aug 17, 2011 at 12:32
  • @J0HN, it was a formatting error. Thanks for the fix. Commented Aug 17, 2011 at 12:37
  • Why theis is not working? You are getting PHP errors, or JS is just not working? If you open "Source View" (Ctrl+U in FF and Chrome, if I'm not mistaking), do you see your script where it should be? Commented Aug 17, 2011 at 12:39
  • @J0HN no errors at all. When I Source View the javascript code is found on the page which means the code is not working properly. Commented Aug 17, 2011 at 12:41
  • Try replacing condition with false, and tell us if that works. Commented Aug 17, 2011 at 12:44

5 Answers 5

2

The best way is to do something like this:

<?php
  if ($something) {
?>
<script>
  alert('hi')
</script>
<?php
  }
?>
Sign up to request clarification or add additional context in comments.

1 Comment

This is not working at all ;(. The script tag is always showing. Is there anything that I should take into consideration?
0

Besides including it in a variable and outputting it conditionally, the only other possibility that I can think of is to put the JavaScript code in a file, and then have a PHP condition which outputs an include for that JavaScript file if it is true.

Comments

0

This doesn't work?

<?php if(condition){ ?>
    <script> ... </script>
<?php } ?>

2 Comments

condition should be $condition, eh?
so is it CONDITION or condition ? :-)
0
<?php 
define('condition', true);
if(condition) { ?> <script> stuff here </script> <?php } ?> 

should work

2 Comments

sorry, the condition is just something I wrote to denote there is a condition here, not a constant. I messed the formatting pretty badly.
it doesn't matter, if condition is true, it's outputed
0

what about hiding or showing the // comment lines with php?

if ($something){
echo "//"; ?>   <script> 
<?php
echo "//"; ?>     alert('hi') 
<?php
echo "//"; ?>   </script> 
<?php

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.