Andres SK
Andres SK

Reputation: 10974

Working with cookies between jQuery and PHP

I save a cookie in PHP:

setcookie('name['.time().']','Andres',time()+86400,'/');

As you can see, it is not a regular cookie value, because it is an array. That helps me to sort() or ksort() the values later.

The user has also a "clear list" button which calls a javascript function. In it, I use:

$.cookie('name',null,{expires:-1,path:'/'});

But it doesn't work, because the cookies are probably being saved as:

etc...

jQuery: How can I delete all cookies that start with "name"?

Upvotes: 0

Views: 432

Answers (2)

Repox
Repox

Reputation: 15476

Try something like this:

$.each(document.cookie.split(/; */), function(cookieString)  {
  var splitCookie = cookieString.split('=');
  // name is splitCookie[0], value is splitCookie[1]
  if(splitCookie[0].indexOf('name[')==0)
    $.cookie(splitCookie[0], null, {expires:-1,path:'/'});
});

Upvotes: 0

Thinker
Thinker

Reputation: 14464

You need to loop through all cookies

var pairs = document.cookie.split(";");
for (var i=0; i<pairs.length; i++){
  var pair = pairs[i].split("=");
  if(pair[0].indexOf('name[')==0) $.cookie(pair[0],null,{expires:-1,path:'/'});
}

Upvotes: 1

Related Questions