Azima Azima - 3 months ago 5
Javascript Question

Redirecting to next page with onclick()

<?php
session_start();
?>
<a href="hola.php" onclick="return check();">Take me</a>
<script type="text/javascript">
function check() {
<?php
if(isset($_SESSION['user'])
return true;
else
return false;
?>
}
</script>


A user will be able to redirect to next page only if he is logged in, otherwise he is prevented to the same page. I've checked for solutions but don't find what I am looking for. Is php script valid inside javascript script?

Answer

One solution using echo to print javascript statements:

<?php
session_start();
?>
<a href="hola.php" onclick="return check();">Take me</a>
<script type="text/javascript">
    function check() {
       <?php 
       if(isset($_SESSION['user']) {
          echo "return true";
       } else {
          echo "return false";
       }
       ?>
    }
</script>
Comments