0

I have 2 php variables in PHP (mainly $usm and $ag) and am passing them to the frontend. In Javascript am using isset to check if they have a value before executing some code but seems not to work

<script>
    if( <?php isset($usm , $ag) ?> ){
        $( document ).ready(function() {
            var usmData = {!! json_encode($usm) !!};
            var agData = {!! json_encode($ag) !!};
        });
    }
</script
Martin
  • 547
  • 2
  • 11
  • 40
  • You may not access the PHP variable within the script. Try to set the php variable in cookies or sessions and extract the php variable data from there. – Ramya Jan 03 '19 at 09:55

4 Answers4

1

You need to check the isset part with PHP only.

<?php if(isset($usm) and isset($ag)){ ?>
<script>
    $( document ).ready(function() {
        var usmData = '<?php echo json_encode($usm); ?>';
        var agData = '<?php echo json_encode($ag); ?>';
    });
</script>
<?php } ?>
executable
  • 3,365
  • 6
  • 24
  • 52
0
<script>
    <?php if(isset($usm , $ag)) { ?> 
        $( document ).ready(function() {
            var usmData = {!! json_encode($usm) !!};
            var agData = {!! json_encode($ag) !!};
        });

    <?php } ?>
</script>
GabrieleMartini
  • 1,665
  • 2
  • 19
  • 26
0

I would suggest you to write the PHP code outside otherwise script tag will be executed unnecessary with empty code if the condition is not met.

<?php 
    if(isset($usm , $ag) {
?>
<script>
    $( document ).ready(function() {
        var usmData = '<?php echo json_encode($usm); ?>';
        var agData = '<?php echo json_encode($ag); ?>';
    });
</script>
<?php
    }
?>
Rajendra arora
  • 2,186
  • 1
  • 16
  • 23
-1

That doesn't make sense. You mixed up PHP and JS.

Result of PHP isset is only used on PHP and doesn't make it to JS side. Your JS if statement is not valid.

Check this article for more info.

MorganFreeFarm
  • 3,811
  • 8
  • 23
  • 46
TuckerS
  • 3
  • 1
  • 4
  • But I placed it inside php tags – Martin Jan 03 '19 at 09:58
  • 1
    @Martin It doesn't matter because Javascript expects a boolean value inside `if` and your the result of your PHP code doesn't get passed to JS. not like that anyway. – TuckerS Jan 03 '19 at 10:01