简体   繁体   中英

Checking if 2 php variables are set inside Javascript isset

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

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.

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 } ?>
<script>
    <?php if(isset($usm , $ag)) { ?> 
        $( document ).ready(function() {
            var usmData = {!! json_encode($usm) !!};
            var agData = {!! json_encode($ag) !!};
        });

    <?php } ?>
</script>

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
    }
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM