Ali
Ali

Reputation: 3666

write javascript to page based on a condition

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.

Upvotes: 0

Views: 2447

Answers (5)

user482024
user482024

Reputation: 95

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

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

}

Upvotes: 0

genesis
genesis

Reputation: 50966

<?php 
define('condition', true);
if(condition) { ?> <script> stuff here </script> <?php } ?> 

should work

Upvotes: 0

Abraham
Abraham

Reputation: 20686

The best way is to do something like this:

<?php
  if ($something) {
?>
<script>
  alert('hi')
</script>
<?php
  }
?>

Upvotes: 2

wanovak
wanovak

Reputation: 6127

This doesn't work?

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

Upvotes: 0

Edoardo Pirovano
Edoardo Pirovano

Reputation: 8334

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.

Upvotes: 0

Related Questions