jquery - PHP updating SESSION or COOKIE via AJAX

335

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("\n");
print("\n");

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

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)
129

Answer

Solution:

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

People are also looking for solutions to the problem: php - Echo statement rendering html code in output

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.