Handling session timeout in ajax call

Handling session timeout in ajax call, How to check session timeout through AJAX call, How to redirect ajax request when session times out, ajax detect session timeout, ajax session timeout redirect, handle session timeout in ajax request.

When we using ajax in user logged in pages we need to handle session timeout in ajax call. If session timeout and user refresh page, process working proper but when session timeout and system fire ajax call process not work proper. It doesn’t work for ajax requests, as you can’t redirect from an ajax request.

For getting expected result from ajax and php combination always write code in such a way that it handle all the possible failures. Below simple good practice given for handling session timeout in ajax call.

PHP code for handle ajax call ( process.php ):

<?php

//START HANDLE AJAX CALL
$returnArr = array();

//CHECK LOGIN STATUS
if(empty($_SESSION['user_id']))
{
    $returnArr['auth_fail'] = true;
    $returnArr['success'] = false;
}
 
//IF PROCESS SUCCESS
$returnArr['success'] = true;
$returnArr['message'] = 'Your message here';

//IF PROCESS FAIL
$returnArr['success'] = false;
$returnArr['message'] = 'Your message here';

//RETURN OUTPUT
header('Content-Type: application/json');
echo json_encode($returnArr);
exit;

?>

Ajax call:

<script>

$.ajax({
    url: "process.php",
    data: '{IF ANY}',
    contentType: 'application/json',
}).done(function(data) {
    if(data.success){
        //PROCESS IF SUCCESSFULLY DONE
    }else if(data.auth_fail){
        //RELOAD PAGE IF AUTH FAIL FLAG SET
        location.reload();
    }else{
        //PROCESS IF CALL FAIL
        alert(data.message);
    }
});

</script>