View Full Version : I need a javascript
Drayven
02-05-2010, 12:58 PM
For some reason this really simple Javascript is evading me, I'm hoping one of you can help me out. All I want to do is check for the existence of a particular cookie, if that cookie exists nothing happens, if the cookie doesn't exist the browser will be redirected to a certain URL. So if the cookie called 'Monkey' doesn't exist the user is redirected to /zoo/.
Thanks for any help you can give :P
LiquidRain
02-05-2010, 03:05 PM
getCookie = function(name) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
} else {
begin += 2;
}
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = dc.length;
}
return unescape(dc.substring(begin + prefix.length, end));
};
var mmm_cookie = getCookie("chocochip");
if (!mmm_cookie) { window.location.href = "/nomilk4u"; };
A bit sloppy since I just copy/pasted getCookie from my (own) framework class, so it may/may not compile, but that's what you're looking at to get a single cookie.
You may want to look around for other code examples or consider adopting a framework that includes cookie parsing. (e.g. MooTools/MooTools.More)
jeffbax
02-06-2010, 08:55 AM
www.jquery.com is your friend.
Don't reinvent the wheel, when it's already there for you (and probably better than you would do reimplementing it yourself)
vBulletin® v3.8.7, Copyright ©2000-2012, vBulletin Solutions, Inc.