check if jquery cookie array exists

I was wondering if it was possible whether jquery can check if a cookie array exists or not.

My cookie name is 'report' and with php I echo it out like this:

echo '<pre>'; print_r($_COOKIE['report'][146]); echo '</pre>';

Which spits out something like this:

Array
(
    [15128] => 15128
    [13670] => 13670
)

This is where I'm hoping to get jquery to check if the above cookie array exists (or not), this is what I've got so far, but it's not picking up the cookie array..

if ( $.cookie('report[146]') ) {
  window.location = 'http://www.myurl.com/';
} else {
  alert('Please make a selection.');
}

My form doesn't refresh when someone ticks a checkbox, but it uses jquery to add the cookie (which works fine), but I can't seem to get jquery to check if there are any cookies.

This is the code where it adds individual cookies to the array:

if ($(this).attr('checked')) { 
  $.cookie('report[146]['+thisID+']', thisID, { expires: 7, path: '/' });
} else {
  $.cookie('report[146]['+thisID+']', thisID, { expires: -1, path: '/' });
};

Any help would be appreciated!

Answers


What you're doing right now is setting cookie that is named report[146]['+thisID+'] (if for example thisID = 135, then cookie name is report[146][135]). Value of the cookie is not an array, the value of that cookie is value of thisID.

If you want cookie to have name report and it's value should be array that at index 146 has value thisID, do the following:

var cookieValue = [];
cookieValue[146] = thisID;

set it:

$.cookie('report', cookieValue);

Cookie value will now be set to (that's the way array is serialized):

,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,135

To read it:

var cookie = $.cookie('report');
if(cookie){
  var cookieValue = cookie.split(','); //you need to do this since array is serialized as comma separated values.
  var valueAtIndex146 = cookieValue[146];
}

if($.cookie('report') == null) { 
    alert('no cookie!');
}

Need Your Help

Getting the character index for a x,y position in a NSString drawn with drawInRect

ios nsstring

I'm currently using NSString's drawInRect to display a font. This is then being uploaded to a texture to be used by OpenGL.

Wordpress, how to start with an empty theme?

wordpress wordpress-theming

I have been working on Wordpress for a month creating themes. Otherwise, when I'm starting a new project, I'm always starting with an existing theme that I am modifying.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.