简体   繁体   中英

Set cookie from CodeIgniter and get the value with javascript

I'm trying to get some data from a cookie. I set the cookie with CodeIgniter and here is my code

$c = array('name' => 'total', 'value' => $total, 'path' => '/');
$this->input->set_cookie($c);

Then, I want to take the data with javascript. This is what i've tried

function getCookie(c_name) {
  var i,x,y,ARRcookies=document.cookie.split(";");
  for (i=0; i<ARRcookies.length; i++) {
    x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
    y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
    x=x.replace(/^\s+|\s+$/g,"");
    if (x==c_name) {
      return unescape(y);
    }
  }
}

console.log(getCookie('total'))

I got the function from here but it doesn't work to my code. Is there anyway to achieve this ?

There's nothing wrong with your javascript codes. Maybe it happens because the cookie is not yet set. You just have to add expire value to your cookie, set it to any number (in seconds) or 0 to set it to disable immediately.

$c = array('name' => 'total', 'value' => $total, 'path' => '/', 'expire' => 0);
$this->input->set_cookie($c);

To read the cookie you can use this

function readCookie(name) {
let nameEQ = encodeURIComponent(name) + '=';
let ca = document.cookie.split(';');
for (let i = 0; i < ca.length; i++) {
    let c = ca[i];
    while (c.charAt(0) === ' ')
        c = c.substring(1, c.length);
    if (c.indexOf(nameEQ) === 0)
        return decodeURIComponent(c.substring(nameEQ.length, c.length));
}
return null;

}

readCookie('total'); This has worked for me multiple times, Hope it works for you as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM