PHP通过AJAX更新SESSION或COOKIE

I'm trying to update a session or a cookie via an AJAX call to a page on the same domain but I keep getting weird results. As soon as the page is refreshed a new session is created when I wanted the old one to persist.

The AJAX called from index.php:

$.ajax({
        type: 'POST',
        url: '/api/cart.php?function=GetCart',
        dataType: 'json',
        async: false,
        data: {
            json: true
        },
        success: function(cart) {
            window.console.log(cart);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {}
});

The PHP in cart.php:

var_dump($_SESSION["test"]);
print("
");
print("
");

$_SESSION["test"] = rand(1, 999);
print("
");
print("
");

var_dump($_SESSION["test"]);
die();

First refresh:

<b>Notice</b>:  Undefined index: test in <b>cart.php</b> on line <b>xxx</b><br />
NULL
int(154)

Second refresh:

<b>Notice</b>:  Undefined index: test in <b>cart.php</b> on line <b>xxx</b><br />
NULL
int(981)

php by default maintains the session on ajax call, use fn: isset() / empty() to check session on ajax call. if session expires login again. second option is, you can increase session timeout duration. how-to-change-the-session-timeout-in-php