简体   繁体   中英

Javascript code giving if condition error in console

<?php
if($_GET['st'] !=''){
$st= $_GET['st'];
?>
    <script>
    var st = <?php echo  $st; ?>
    if(st !=''){
        console.log('got function here');
    }
    </script> 
<?php }?>

i want to show if the $st is not equal to empty then do something else do something else but its giving error

pro.php?st=foo:13 Uncaught SyntaxError: Unexpected token if.

try this,

<?php
  if($_GET['st'] !=''){
  $st= $_GET['st'];
?>
<script>
  var st = "<?php echo  $st; ?>"; // assign var st properly with ("st";)
  if(st !=''){
  console.log('got function here');
  }    
</script> 
<?php 
}
?>

Instead of st = <?php echo $st; ?> st = <?php echo $st; ?> use st = "<?php echo $st; ?>"; , You need to close the statement of PHP and javascript.

<?php
if($_GET['st'] !=''){
$st= $_GET['st'];
?>
    <script>
    var st = "<?php echo  $st; ?>";
    if(st !=''){
        console.log('got function here');
    }
    </script> 
<?php }?>

You need to store st inside the quotes, something like that:

var st = '<?=$st?>';

But before that, you also need to use isset() for checking either $_GET['st'] set or not along with !empty() condition.

Example:

<?php
if(isset($_GET['st']) && !empty($_GET['st'])){
  $st = $_GET['st'];
?>
    <script>
    var st = '<?=$st?>';
    if(st != ''){
      console.log('got function here');
    }
    </script> 
<?php 
}
?>

Note that, you have already check the empty value in PHP , don't know why are you using it again in javascript .

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