سؤال

im receiving a json file from an external call. If the json comes with a null value (possible if the user session is expired) then the user should be redirected to the logout.php page. In my current call, instead of redirecting, the logout.php data is being received as a json response.

So, how do I redirect the user when the json data is null?

$.getJSON(sSource, aoData, function (json) {
    if(json !== null) {
        fnCallback(json);
    } else {
        window.location.href = "logout.php";
    }
});

Thanks to @Ron's observation i noticed that, although sSource was calling the right file (datatables.php), its header isn't detecting the request method, hence returning the wrong data:

if(($_SESSION['login_expire'] + $session['expiration_time']) < time()) {
    if($_SERVER['REQUEST_METHOD'] == 'POST') {
        # forms
    } else {
        if(strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
            # datatable
            header('Content-type: application/json');
            echo json_encode(null);
        } else {
            # get
            header('Location: '.URL_CMS.'logout.php?expired=true');
        }
    }
    die();
} else {
    # update expiration time
    $_SESSION['login_expire'] = time();
}

That last bit controls idle times. It should also consider ajax calls, in which case it should return a json_encode(null) string instead of redirecting via php:

if(strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')

هل كانت مفيدة؟

المحلول

What you want is for your PHP to return some JSON that includes a response status and then use that response to send them to the error page if it's a bad status. For example, have your PHP return {"status":"failed", "message":"Expired"} instead of setting the Location header like it is currently.

Then in your Javascript:

if(json.status != "failed") {
    fnCallback(json);
} else {
    window.location.href = "logout.php";
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top