开发者

PHP/AJAX check if session variable changed

开发者 https://www.devze.com 2023-01-11 20:28 出处:网络
Greetings! I need to dynamically check if a session variable changes every few seconds. F开发者_运维知识库or example, the PHP session variable \"x\" may have a value of \"1\", and then after five sec

Greetings!

I need to dynamically check if a session variable changes every few seconds. F开发者_运维知识库or 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?


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'];
?>


i did like this in my code

<script>
    function myFunction() {
    var name = document.getElementById("name").value;
    var email = document.getElementById("email").value;
    var password = document.getElementById("password").value;
    var phone = document.getElementById("phone").value;
    // Returns successful data submission message when the entered information is stored in database.
    var dataString = 'name=' + name + '&email=' + email + '&password=' + password + '&phone=' + phone;
    if (name == '' || email == '' || password == '') {
        alert("Please fill all fields");
    } else {
    // AJAX code to submit form.
        $.ajax({
            type: "POST",
            url: "signupAjax.php",
            data: dataString,
            cache: false,
            success: function(html) {

            var isRegistered = '<?php echo $_SESSION['name'];?>';
            var url = '<?php $url = $site_root.'index.php'; echo $url;?>';

            if(isRegistered.length > 0)
            {
                window.location = url;
            }
            else
            {
                alert(html);
            }

            }
        });
        }
        return false;
    }
</script>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号