sukkis
sukkis

Reputation: 322

How to redirect index.php page if session checking with jquery fails in the background?

I have one index.php which requires session. Also I have sessioncheckpage.php

which look like code below. It works well.

$login_hash=$_SESSION['hash'];
if ($login_hash != $tulos) {
    session_destroy();
    header("Location: login.php");
}

But how can I reload index.php? My Javascript code just would to refresh sessioncheckpage.php in the background.

<script>
var interval    =   0;
function start(){
    setTimeout( function(){
        ajax_function();
        interval    =   10;
        setInterval( function(){
            ajax_function();
        }, interval * 1000);
    }, interval * 1000);    
}

function ajax_function(){
    $.ajax({
        url: "sessionchecker.php",
        context: document.body,
        success: function(result){
            $('.time').html(result);
        }
    }); 
}

$( window ).load(function(){
    var time    =   new Date();
    interval    =   10 - time.getSeconds();
    if(interval==10)
        interval    =   0;
    start();
});
</script>

Above is jQuery which is included in index.php. Also it would be possible to reload index.php as a sessioncheckpage.php but there is video content so video should not stop after page refresh (session checking)....

Upvotes: 3

Views: 384

Answers (2)

Kld
Kld

Reputation: 7068

You can check the status code

PHP Code

<?PHP 
if(notLoggedIN()){
    header("HTTP/1.1 401 Unauthorized");
    exit;
}
?>

jQuery

$.ajax({
    url: "sessionchecker.php",
    context: document.body,
    success: function(result){
        $('.time').html(result);
    }
    error: function(jqXHR, status, code){
        if (jqXHR.status === 401) {
           window.location.replace("/login.php");
        }
    }
}); 

Upvotes: 3

Chris Watts
Chris Watts

Reputation: 6715

If your sessionchecker script is RESTful (i.e. implements HTTP error codes), then add to your $.ajax call an error function. Otherwise, add a clause in your success function to call window.location.reload()

$.ajax({
    url: "sessionchecker.php",
    context: document.body,
    success: function(result){
        $('.time').html(result);
    }
    error: function(jqXHR, status, error){
        window.location.reload();
    }
}); 

Upvotes: 0

Related Questions