0

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)
Bhumi Shah
  • 9,323
  • 7
  • 63
  • 104
  • 1
    Is that the whole cart.php or does it contain more code?? – Kypros Oct 06 '14 at 11:37
  • Do you have `session_start()` at the beginning of the `PHP` file? – XCS Oct 06 '14 at 11:38
  • Yes I have a session_start, a basic framework is included before the cart.php, that's just the bit of code that is executed. – Mikkel Nordskjold Oct 06 '14 at 11:39
  • Are you setting the session id before session_start() try using session_id($_COOKIE['PHPSESSID']) or what ever you called your session name. The default will be PHPSESSID. I havent tested this but I'm assuming its starting a new session each time. Also try setting session_save_path() to a path on your computer in order to see exactly what is being saved in the session each time. – Jacques Koekemoer Oct 06 '14 at 11:43
  • I just tryed dumping session_id() in cart.php which is called via AJAX and it seems to persist through several refreshes. And it is being set before session_start. – Mikkel Nordskjold Oct 06 '14 at 11:51

1 Answers1

0

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

Community
  • 1
  • 1
valar morghulis
  • 2,007
  • 27
  • 34
  • A timeout doesn't seem to be the problem. Since sessions work fine for the rest of my project. The problem is that the PHP page requested through the AJAX call gets treated like a new client visiting the page. – Mikkel Nordskjold Oct 06 '14 at 11:55
  • use print_r($_SERVER); check the variable PHPSESSID for normal request as well as ajax request, you will find an answer. – valar morghulis Oct 06 '14 at 12:13
  • No not really since $_SERVER doesn't return anything regarding session id. The array returned match eachother on both the index.php and cart.php – Mikkel Nordskjold Oct 06 '14 at 13:07