Search code examples
javascriptphpnoscript

Setting PHP variable in <noscript>


Something like the below does not work:

<?php $nojs = false; ?>
<noscript>
    <?php $nojs = true; ?>
</noscript>

As the PHP is executed regardless if JS is enabled or not. But is there a way to get a similar effect? I'm trying to set a flag if JS is disabled and then display parts of the page accordingly.


Solution

  • PHP is executed before javascript, so you cannot do this. You can do something such as executing a basic ajax request and storing hasjs in a session variable once the ajax page is successfully queried. You wouldn't know if it's just the fact that the ajax request wasn't successful due to something else, or if they have Javascript disabled.

    Lets give this a shot anyway:

    The jquery script in your head tags

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <script>
    $( document ).ready(function() {
        $.get( "hasjs.php", { hasjs: "1"} );
    });
    </script>
    

    The PHP file (hasjs.php)

    <?php
    if(isset($_GET['hasjs']))
    {
        session_start();
        $_SESSION['hasjs'] = 1;
    }
    ?>
    

    Then you can access the session variable to determine if they have JS based off the ajax query. Nothing stopping the user from visiting that page though if they don't have JS installed.