Display Tutorials

  Home arrow Display Tutorials arrow Page 2 - Smart Auto Refresh
DISPLAY TUTORIALS

Smart Auto Refresh
By: Codewalkers
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 16
    2005-04-05

    Table of Contents:
  • Smart Auto Refresh
  • Coding Time

  •  
     

    SEARCH CODEWALKERS

    Smart Auto Refresh - Coding Time


    (Page 2 of 2 )

    I know you are lazy typists, so before you get nervous I would like to let you know that you don't need to write down all the code that I give here. The files are all in zip format and ready for action and just need some modification of course.

    <!--//
        @filename index.html
        @desc This is the main page of shoutbox
    //-->
    <iframe name='chatroom' src='chat.php' width=200 height=300 border=1></iframe>
    <form name='chatform' method='post' target='chatroom' action='chat.php'>
    Name: <input type='text' name='name'><br>
    Message: <input type='text' name='message'><br>
    <input type='submit' name='action' value='Submit'>
    </form>

    As you see, there is an iframe named 'chatroom', and a simple form with 2 fields: name and message. When we execute the form by entering the values in the fields, then hit enter or click on the submit button, it will execute a file named chat.php which is loaded on the iframe page. So what does the chat.php file look like? Here it is:

    <?php
    /**
    * @filename chat.php
    * @desc This is the processor and the viewer of the visitors message
    */
    $conn = mysql_connect ('localhost', 'root', 'letmein');
    @mysql_select_db ('test', $conn);
    if (isset ($_POST))
    {
        $name = ((isset ($_POST['name']) 
                  && trim ($_POST['name']) != '') 
                  ? trim($_POST['name']) : '');
                  
        $message = ((isset ($_POST['message']) 
                     && trim ($_POST['message']) != '') 
                     ? trim($_POST['message']) : '');
                     
        $name = mysql_escape_string ($name);
        $message = mysql_escape_string ($message);
        
        if ($name != '' && $message != '')
        {
            $sql = "INSERT INTO chat (name, message, msgdate) "
                 . "VALUES ('$name', '$message', NOW())";
            @mysql_query ($sql, $conn);
            $mytime = time();
            touch ('sar.pid', $mytime);
            setcookie ('pid', $mytime, time()+(60*60));
            $redir = dirname('http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'])
                   . '/chat.php';
            Header ('Location:'.$redir);
            exit();
        }
    }
    ?>
    <script language='JavaScript1.2'>
    <!--
    function sar(mytime)
    {
        img = new Image;
        img.src = 'detector.php';
        pid = read_cookie('pid');
        if (pid > mytime)
        {
            var mytime = pid;
            write_cookie ('mytime', mytime, 1);
            document.location.href = 'chat.php';
        }
        setTimeout('sar('+ mytime +')', 2000);
    }
    function read_cookie (name)
    {
        var cookieValue = "";
        var search = name + "=";
        if(document.cookie.length > 0)
        { 
            offset = document.cookie.indexOf(search);
            if (offset != -1)
            { 
                offset += search.length;
                end = document.cookie.indexOf(";", offset);
                if (end == -1) end = document.cookie.length;
                cookieValue = unescape(document.cookie.substring(offset, end))
            }
        }
        return cookieValue;
    }
    function write_cookie(name, value, hours)
    {
        var expire = "";
        if(hours != null)
        {
            expire = new Date((new Date()).getTime() + hours * 3600000);
            expire = "; expires=" + expire.toGMTString();
        }
        document.cookie = name + "=" + escape(value) + expire;
    }
    function start(mytime)
    {
        write_cookie ('mytime', mytime, 1);
        sar (mytime);
    }
    start (<?=time();?>);
    -->
    </script>
    <?php
        $sql = 'SELECT * FROM chat ORDER BY msgdate DESC LIMIT 0,30';
        $result = @mysql_query ($sql, $conn);
        if (mysql_num_rows ($result) >= 1)
        {
            while ($RS = mysql_fetch_array($result, MYSQL_ASSOC))
            {
                print '<b>'.$RS['name'].':</b> '.$RS['message'].'<br>';
            }
        }
    ?>

    Pay attention to this chat.php file. It contains 3 sections. The first section is the form processor, followed by the JavaScript functions that detect the sar.pid and compare it to existing cookies, and the last section is the message viewer.

    I don't think it is necessary to explain the first and the last section because I believe you already know how it works. The first section inserts the data after some data validation procedure and the last section retrieves the content from the database to be displayed on the message window.

    What we need to focus on is the second section, the JavaScript part. An explanation about this JavaScript is as follows.

    When we open the chat.php the first time in the iframe, it loads the function start with current time (taken from PHP) as the input variable.

    The start function calls the write_cookie function in order to place a cookie, named 'mytime', in the user's browser with the content being the timestamp. After setting the cookie it then loads the sar function, which is the main function that makes everything work.

    This sar function is auto looped every so many milliseconds to do the following:

  • Load the detector.php page and save the cookie value.
  • Compare the value from detector.php with the existing timestamp.
  • If the existing timestamp is older than the one we have from detector.php, then it will save the new value and order the page to reload. Otherwise it will just stop right there and wait for another loop to be initiated.

    The content of detector.php file is:

    <?php
        $mytime = filemtime ('sar.pid');
        if ($mytime < $_COOKIES['mytime']) $mytime = $_COOKIES['mytime'];
        setcookie ('mytime', $mytime, time()+(60*60));
    ?>

    It's just a simple file which detects the timestamp of the sar.pid file and compares it to the existing cookie named mytime. If the file timestamp is lower than the new one, then the new timestamp would be just the same as the mytime cookie. Otherwise, the new timestamp will be the one we get from the filemtime function.

    That's how to make it folks. Get the zip file here and then try it out. Do some modifications and let me know how it goes. If you have any more questions, feel free to drop me a line.

    About The Author

    Hermawan Haryanto is a Web Application Developer with over eight years of Website development experience; provide web application development services internationally. Senior programmer at Red Rock Reef LLC in Las Vegas, United States, Web Application Developer at Swiss German University in Jakarta, Indonesia.


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.
    blog comments powered by Disqus
  • DISPLAY TUTORIALS ARTICLES

    - Smart Auto Refresh
    - Writing a Template System in PHP

    Developer Shed Affiliates

     



    © 2003-2019 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap