0

In a task I had, I needed to create a boolean variable that persists in a user's session, so I thought of a cookie (I'm using Prestashop, so that would be $this->context->cookie->myVariable).

The user would check a checkbox in a page, this would trigger an AJAX request to a script that changes the relevant cookie's value. After the AJAX request succeeds, I expect further requests/reloads to the webpage to render slightly different, based on the value of the cookie.

My approach works perfectly on localhost, but on our production website (that includes a Cloudflare CDN), it keeps showing the old value of the cookie variable. Could this be the CDN caching the old cookie value? Or am I doing something wrong here?

Below is the PHP script that sets the variable:

<?php

include_once('./config/config.inc.php');
include_once('./config/settings.inc.php');
include_once('./classes/Cookie.php');

$context = Context::getContext();

//switching the value of myVariable
if(!$context->cookie->myVariable) {
    $context->cookie->__set('myVariable', true);
}

else {
    $context->cookie->__set('myVariable', false);
}

die("Success!");

And the Javascript code of the ajax request:

$.post("url/of/script", null, function(res) { 
    if(res.includes("Success")) {
        //do something on success
        //I expect this request to have changed the cookie's value, so that on further requests I would get the right results displayed. It is not the case on production site only.
    }
 });
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Anis R.
  • 6,656
  • 2
  • 15
  • 37

1 Answers1

0

After further research, I came across this answer, which saved my life!

I did know about the Cache-control header, and tried using it before posting this question, but it did not work. Turns out I needed to place it before setting the cookie, not after! Same applies for the Location header, which I currently also added because of the functionality I wanted to implement.

Bottom line: If you want to use Cache-control and Location headers, specify them before changing the cookie, not after!!

My updated PHP code:

<?php

include_once('./config/config.inc.php');
include_once('./config/settings.inc.php');
include_once('./classes/Cookie.php');

//the mighty headers!!
header("Location: $redirect_url"); //redirect - a functionality I need now
header('Cache-control: no-store, no-cache, must-revalidate'); //cache control header


$context = Context::getContext();

if(!$context->cookie->made_in_lb) {
    $context->cookie->__set('myVariable', true);
}

else {
    $context->cookie->__set('myVariable', false);
}
Anis R.
  • 6,656
  • 2
  • 15
  • 37