I created a function to get the cookie in javascript :
function getCookie() {
var arr = document.cookie.split(";");
for (i = 0; i < arr.length; i++) {
if (arr[i].substr(0, arr[i].indexOf("=")).replace(/^\s+|\s+$/g, "") == "taxibleC") {
return arr[i].substr(arr[i].indexOf("=") + 1);
}
}
}
var multipleVAT = 1;
And then I have another function to initialize the cookie :
function ChangeVATValue()
{
if ($("#vatEnable").is(':checked')) {
multipleVAT = 1;
} else {
multipleVAT = 0;
}
document.cookie = "taxibleC=" + multipleVAT;
alert(getCookie());
}
When I used alert(getCookie());, It has the value 1.
But when I click to another page, the alert is 0.
Could anyone tell me, why I cannot access the session by using the getCookie() method in the view of my asp.net MVC 3.0 project.
That is because you cookie might get expire immediatly, if possible se cookie expiration time to certail limit and than access the value of cookie on another page that resolve your issue
something like
document.cookie =
'ppkcookie1=testcookie; expires=Thu, 2 Aug 2001 20:47:11 UTC; path=/'
You need to set path in the cookie for accessing in different page
;path=/
For example,
document.cookie = 'YOUR COOKIE DATA;path=/'
Related
I'm having problem of creating a cookie, I have this code:
window.onload = function() {
var value = readCookie('username');
if(value == null){
alert("null");
document.cookie = "username=Bob; expires=Thu, 18 Dec 2016 12:00:00 UTC";
}
else
alert(value);
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
When the page load I check if the cookie exists, if it doesn't, I pop up an alert saying that is null, then I create the cookie, but every time I load the page it always says its null. Now the problem is in the creation of the cookie or in the readCookie function. I can't find why this doesn't work.
UPDATE
So in google Chrome it won't work, but in internet explorer works perfectly, someone knows why? I would like to work in all browsers.
When I create an HTML page using that code and run it in a normal test environment, the problem you describe does not occur. It alerts null on the first load and Bob on the second load.
If, however, I tell the browser to load the page from file:///Users/david/tmp/jgfklgjkl/index.html instead of my test server at http://localhost:7007/, then it always alerts null.
Cookies are associated with a hostname, and you have to load the page over HTTP in order to use them.
You are presumably loading them from a local file, and that is where the problem lies, not with your code.
Try this function for reading cookie. I've been using it for quite too long and it's working fine so far
function getCookieValue(cookie_name) {
var cookie, cookies = document.cookie.split(';');
for (var i = cookies.length - 1; i >= 0; --i) {
cookie = cookies[i].split('=');
if (cookie[0].trim() === cookie_name)
return cookie[1];
}
return "";
}
Also if you are interested you could use this function for adding cookies for 10 years.
function addCookie(name, value) {
var expire = new Date();
expire.setFullYear(expire.getFullYear() + 10);
d.cookie = name + "=" + value + "; expires=" + expire.toGMTString() + "; path=/";
}
I am trying to set up a conditional cached re-direct depending on the website viewers choice.
Here's an example of how I am looking to have the website function ( you can test this by going to vonage.com):
When I visit www.vonage.com, I have a choice between "For Personal, For Small Business, For Mid-Market & Enterprise".
After making the choice, you'll be sent to the associated website/subdomain - either vonage.com, personal.vonage.com, or enterprise.vonage.com.
Then, if you try to go back to the initial page with choices, you won't be able to, you're redirected back to the choice that you've already made.
How is this done? I would like to implement something similar. I'm using Wordpress by the way, but that probably won't matter, I can get my hands dirty in the code or .htaccess.
There may be a better way, and this is java-script only not php, but a cookie should do the trick.
on page load check if the cookie exists, if it does redirect, if not don't:
if (document.cookie.indexOf("home") >= 0) {
// redirect them to home
}
else if (document.cookie.indexOf("business") >= 0) {
// redirect them to business
}
else if (document.cookie.indexOf("enterprise") >= 0) {
// redirect them to enterprise
}
if none of those trigger, and the user is not redirected when they choose an option set their cookie, for example:
// set a new cookie
expiry = new Date();
expiry.setTime(date.getTime()+(10*60*1000)); // Ten minutes
// Date()'s toGMTSting() method will format the date correctly for a cookie
document.cookie = "business; expires=" + expiry.toGMTString();
(function(href, referrer) {
var enterprise = "http://enterprise.mysite.com"
var personal = "http://personal.mysite.com"
var is_enterprise = new RegExp(enterprise).test(href)
var is_personal = new RegExp(personal).test(href)
var cache = readCookie('portal')
if (cache) return location.href = cache
var portal = is_enterprise || is_personal
if (portal) document.cookie = "portal=" + (enterprise || personal) + "; expires=Fri, 31 Dec 9999 23:59:59 GMT";
return null
})(location.href, document.referrer)
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
I have a blog that requires users to signup via email in order to view the full post. I want to skip this requirement if a user has already signed up.
Here's how it works.
User visits page, if cookie is presen then show content
If cookie is not present, user must signup
User signs up, cookie created.
The problem with my code is that it's post specific. e.g. Let's say we have Post A & Post B. If user opts in Post A, they will need to opt in again on Post B which is not good.
If they opt in on Post A, I want to recognize the cookie on Post B as well.
How can I adjust my code?
if (document.cookie.indexOf("entered_email")>=0) {
jQuery('.hidden-blog').slideDown();
}
$('.snp-subscribeform').on('submit', function() {
$('.hidden-blog').slideDown();
document.cookie="entered_email=true;expire=06/12/2018";
});
You need to set the path on the cookie to "/" which then allows any page on that site to see the cookie. When you do not set a path for the cookie value, it defaults to the path of the current page which restricts the visibility of that cookie to that path only.
Here are some utility functions for dealing with cookies that allow you to set the path or will default the path to "/".
Using these, your code would look like this:
if (readCookie("entered_email") === "1") {
jQuery('.hidden-blog').slideDown();
}
$('.snp-subscribeform').on('submit', function() {
$('.hidden-blog').slideDown();
// cookie path in this function defaults to "/" so all pages on the
// site can access the cookie
createCookie("entered_email", "1", 365 * 3);
});
And, here's the utility cookie management functions:
// createCookie()
// name and value are strings
// days is the number of days until cookie expiration
// path is optional and should start with a leading "/"
// and can limit which pages on your site can
// read the cookie.
// By default, all pages on the site can read
// the cookie if path is not specified
function createCookie(name, value, days, path) {
var date, expires = "";
path = path || "/";
if (days) {
date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires=" + date.toGMTString();
}
document.cookie = name + "=" + value + expires + "; path=" + path;
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
I am trying to comply with new EU law for cookie legislation and need to remove all the cookies on my site before the user consents to it. Currently I've used the following successfully:
function deleteAllCookies() {
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i];
var eqPos = cookie.indexOf("=");
var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
}
However once this process runs there is still as a cookie called ASP.NET_SessionID which is created by ASP.NET. To overcome this I set the following in the web.config file which basically stores the sessionID in the URL:
<sessionState regenerateExpiredSessionId="true" cookieless="true" />
The problem I have is when I set cookieless="true" the javasscript code above doesn't remove any of my cookies anymore, its like its become redundant. When I set cookieless="false", the javascript works perfectly. Are there any other settings I need to change to get both to work together?
Thanks
If you don't need session, you can disable sessionstate (mode="Off")
Also, I usually cleanup the cookies server-side, like this (never looked if it removed asp.net sessionid though) :
protected void Page_Load(object sender, EventArgs e)
{
Response.BufferOutput = true;
Session.Abandon();
HttpCookieCollection cookies = Request.Cookies;
var cookiesList = new List<String>();
foreach (String cookieKey in cookies)
cookiesList.Add(cookieKey);
foreach (var cookieKey in cookiesList)
{
var cookie = new HttpCookie(cookieKey);
cookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(cookie);
}
}
Hope this can help.
I've been out of web development for a while now so very rusty.
I need to make a cookie
If the user visits the site > set cookie
If user comes back to site > read cookie
If time since user last arrived is less than 24hrs > set the ID of a div to style="display:none;"
im struggling and would really appreciate some guidance.
thanks so much
With JavaScript you can
- read cookie:
var coo = [],
a;
if(document.cookie != ''){
$.each(document.cookie.split('; '), function(i, val){
a = val.split('=');
coo[a[0]] = a[1];
});
}
here we have a coo with all cookies (coo['Cookie1'] == 'value').
- set cookie:
document.cookie = 'Cookie_1='+'value for this cookie';
BTW code is using jQuery for $.each.
Heres the messy solution i cam up with in case anyone wanted to know:
function nameDefined(ckie,nme)
{
var splitValues
var i
for (i=0;i
tvalue=getCookieValue(nvpair,cname) //Gets the value of the cookie
if (tvalue == cvalue) return true
else return false
}
else return false
}
function redirectLink() {
if (testCookie("here10", "yes")) {
//window.location="here.html" //Go to the location indicating the user has been here
//alert("there");
window.document.getElementById("indicator").style.display = "none";
}
else{
//alert(" not there");
var futdate = new Date() //Get the current time and date
var expdate = futdate.getTime() //Get the milliseconds since Jan 1, 1970
expdate += 10000 //expires in 1 hour(milliseconds)
futdate.setTime(expdate)
var newCookie="here10=yes; path=/;" //Set the new cookie values up
newCookie += " expires=" + futdate.toGMTString()
window.document.cookie=newCookie //Write the cookie
// window.location="not.html" //Go to the location indicating the user has not been here
window.document.getElementById("indicator").style.display = "block";
}
}