views:

115

answers:

1

Greetings!

I need to dynamically check if a session variable changes every few seconds. For example, the PHP session variable "x" may have a value of "1", and then after five seconds, has a value of "2".

The PHP session variable "x" is changed by using a form. If the session variable changes, I need the page to reload.

How can I reload the page if the session variable changes without refreshing the page manually?

A: 

AJAX is a good solution for something like this. Just make a request to script that will return the current value for the session variable. If it is different, then reload.

So, when your page first loads, you have something like

NOTE: This example is relying on jquery library.

<script type="text/javascript">
    var currentSessionValue = <?php echo $_SESSION['something']; ?>;
    // pseudo code
    setTimeout(checkVariableValue, 5000);
    function checkVariableValue() {
         $.ajax({
            url: 'checkMyValue.php',
            success: function(newVal) {
                if (newVal != currentSessionValue);
                    currentSessionValue = newVal;
                    alert('Value Has Changed.');
                    doSomethingDifferent_or_refreshPage();
                }
         });
    }
</script>

checkMyValue.php

<?php
     start_session();
     echo $_SESSION['myVariable'];
?>
sberry2A
Could you provide some code as an example? I am a novice with AJAX.
John Coder
Thanks. What would PERFORM_AJAX_REQUEST look like? And do you know if the PHP session variable can be obtained without calling another file?
John Coder
Once the page has loaded, the only way will be by performing an additional request to get the current state of the $_SESSION data.
sberry2A