Sending time counter to next page

Discussion in 'JavaScript' started by php_guest, Dec 20, 2010.

  1. #1
    I have a situation where I don't know how to search for solution, please help me:

    User gets for every minute staying on the site 1 credit. Credit is updated each minute, even if the page is not reloaded. But also if the page is reloaded or user continue browsing to other pages inside our site, counter should continue where it stayed in the previous page. If the user leaves the site it doesn't need to continue.

    How would you do this? Is it possible to send in javascript value to the next page? Otherwise I have some other ideas, but I am not sure which is the most common:
    1.
    On page leave (if this exists in javascript?) call with ajax timer.php where you assign time to the session.
    2.
    On each 5 seconds call with ajax timer.php where you assign time to the session.
    3.
    Do sql call for each 5 seconds. I guess this is not ok because it is too wasting.

    4.
    Any other solution?

    Thank you
     
    php_guest, Dec 20, 2010 IP
  2. tvoodoo

    tvoodoo Active Member

    Messages:
    239
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    53
    #2
    
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
        <script>
        var interval;
        
        function send() {
            $.ajax({
                type : 'POST' ,
                data : { check: "1" } ,
                url: 'addCredit.php',
                cache: false,
                error: function( objAJAXRequest, strError ){
                    alert('Could not add the credit !');
                }
            });
        }
        
        $(document).ready(function(){
            interval = setInterval("send()",60000);
            
            $(window).bind('unload', function(){
                clearInterval(interval);
            });    
        });
        </script>
    
    HTML:
    Why do you need to keep the time in a session variable ?
    The above script runs once every 1 minute posting to the field addCredit.php the variable $_POST['check'] = 1.
    So in your addCredit.php you can just do :

    
    <?php
        $isAJAX = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && (strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
        
        if($isAJAX && isset($_POST['check']) && $_POST['check'] == 1)
        {
            //the code you want to use to add the credit
        }
    ?>
    
    PHP:
     
    tvoodoo, Dec 20, 2010 IP