Search code examples
javascriptphpjqueryalertify

PHP load javascript function on top of file


This topic is the follow-up of this one PHP + Session doesn't login at first time.

I've solved my issue of Cookies/Sessions by changing the code to the top of everything, before <html>, previously I was writing my php code after the </html> tag.

With this change I've lost the output of javascript plugin (http://fabien-d.github.io/alertify.js/).

Simple example:

if(Cookie::Exists('page-main-login-cookie')){
    echo "<script type='text/javascript'>page_add_success('OK')</script>";
}

This no longer works, I do understand why, because the javascript files are AFTER the <html>, and I'm calling the function before.

<script src="js/alertify/js/alertify.min.js"></script>
<script type="text/javascript">
    function page_add_success(msg){
        alertify.success(msg);
    }
</script>

I've found some topics on stackoverflow about including the right scripts before calling the function in php. Something like:

<?php 
    echo "<script src='js/jquery-1.9.1.min.js'></script>";
    echo "<script src='js/jquery.mobile-1.3.2.min.js'></script>";
    echo "<script src='js/alertify/js/alertify.min.js'></script>";
?>

So, in the end, the top of my file would be:

include('headscript.php');

if(Cookie::Exists('page-main-login-cookie')){
    echo "<script type='text/javascript'>page_add_success('OK')</script>";
}
<html>
    <head>
    <script type="text/javascript">
        function page_add_success(msg){
            alertify.success(msg);
        }
    </script>
    </head>
</html>

But the function continues to be on below of the PHP..and doesn't work. Any ideas? Thanks.


Solution

  • I guess this helps,

    instead of echoing it in php, pass it to a variable and use after the header.

    eg:

      <?php 
       if(Cookie::Exists('page-main-login-cookie')){
        $page= "<script type='text/javascript'>page_add_success('OK')</script>";
            }
      ?>
    

    and then echo it after the header using,

       <?php echo $page; ?>