Search code examples
javascriptphpformspageloadalertify

How to use JavaScript Alertify on page load?


I have a form in a page that submits to itself. In the PHP portion I check

if($_SERVER['REQUEST_METHOD'] == 'POST')

and then I run few things. I am attempting to show an alert using the Alertify suit if something was posted. But on page load I get error

alertify is not defined

I guess it only does that because the page did not load the include links to the js/css files yet (looking in FireFox's FireBug I see the Alertify script line loading before the <html> tag). What can I do to make it work right?

UPDATE CODE:

<?php 
    if($_SERVER['REQUEST_METHOD'] == 'POST') {
        echo '<script type="text/javascript">alertify.alert("Hello");</script>';
    }
?>
<html>
    <head>
        <title>Hello There</title>
        <!--  Alertify Includes -->
        <script type="text/javascript" src="alertify.js"></script>
        <link rel="stylesheet" type="text/css" href="alertify.core.css">
        <link rel="stylesheet" type="text/css" href="alertify.default.css">        
    </head>
    <body onLoad="onLoad()">
        <form action="" method="POST" id="CONFIRM">                          
            <input  class="txt" value="" type="text" name="myName" id="myID" onKeyUp="" onChange="" onFocus="" />
        </form>
    </body>
</html>

Solution

  • After you posted the sources, I think I know what is wrong:

    <?php 
        if($_SERVER['REQUEST_METHOD'] == 'POST') {
        echo '<script type="text/javascript">alertify.alert("Hello");</script>';
        }
    ?>
    

    is located above the script tag that loads your javascript. This means that any code in the PHP segment is executed before that code. In other words, alertify has not yet been defined there.

    To resolve this, place a PHP echo inside the head, below the include for alertify, or include the alertify as a separate echo in the PHP, example:

    <?php 
        if($_SERVER['REQUEST_METHOD'] == 'POST') {
        echo '<script type="text/javascript" src="alertify.js"></script>'
        echo '<script type="text/javascript">alertify.alert("Hello");</script>';
        }
    ?>