setting js simple cookie - javascript

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";
}
}

Related

Javascript checking for cookie values

I have a temporary login script, that checks a password, assigns a cookie, and then redirects the user to a new page. On the console page, I have code that checks if the cookie is set to true. If it is, it deletes it and continues. If it isn't, it redirects the user back to the homepage. I got all the code in place, but it doesn't work! Here's some more important info:
The cookie is called login
the logged in cookie is set to true
The cookie sets properly, it's a problem with the console page's code.
Here's my code:
function getCookie(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;
}
}
// because unescape has been deprecated, replaced with decodeURI
//return unescape(dc.substring(begin + prefix.length, end));
return decodeURI(dc.substring(begin + prefix.length, end));
}
function doSomething() {
var myCookie = getCookie("login");
if (myCookie == true) {
alert("Logged in for one session!");
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
}
else {
alert("Login Failed. Redirecting...");
window.location.assign("https://www.code-u.org/")
}
}
Two years too late to help you, but it's because this widely copypasted getCookie has an error in it.
Namely it does not work if the cookie set is the first cookie in document.cookies, because when the branch if (begin == -1) is taken, end is never set.
The solution would be to replace the getCookie with another implementation.

use saved variable in cookie with php

For last two weeks I was working on saving a page id in cookies and then retrieve it in some other page.
Finally I solved it but now I have some other problem I want to use this id (the one I saved in cookie and retrieve it) in my php code .
I know javascript is client side code and php is server side code but I have to do this. Please help me out with this.
This is my javascript code which is working great and I get the saved id with this line "+value.favoriteid+"
<script>
/*
* Create cookie with name and value.
* In your case the value will be a json array.
*/
function createCookie(name, value, days) {
var expires = '',
date = new Date();
if (days) {
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = '; expires=' + date.toGMTString();
}
document.cookie = name + '=' + value + expires + '; path=/';
}
/*
* Read cookie by name.
* In your case the return value will be a json array with list of pages saved.
*/
function readCookie(name) {
var nameEQ = name + '=',
allCookies = document.cookie.split(';'),
i,
cookie;
for (i = 0; i < allCookies.length; i += 1) {
cookie = allCookies[i];
while (cookie.charAt(0) === ' ') {
cookie = cookie.substring(1, cookie.length);
}
if (cookie.indexOf(nameEQ) === 0) {
return cookie.substring(nameEQ.length, cookie.length);
}
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
var faves = new Array();
$(function(){
var favID;
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
var favID = (pair[0]=='ID' ? pair[1] :1)
//alert(favID);
}
$(document.body).on('click','#addTofav',function(){
var fav = {'favoriteid':favID};
faves.push(fav);
var stringified = JSON.stringify(faves);
createCookie('favespages', stringified);
location.reload();
});
var myfaves = JSON.parse(readCookie('favespages'));
if(myfaves){
faves = myfaves;
} else {
faves = new Array();
}
$.each(myfaves,function(index,value){
var element = '<li class="'+index+'"><h4>'+value.favoriteid+'</h4> ';
$('#appendfavs').append(element);
});
});
</script>
Read cookie on php side it is easiest thing after you set them by js.
Any cookies sent to you from the client will automatically be included
into a $_COOKIE auto-global array if variables_order contains "C". If
you wish to assign multiple values to a single cookie, just add [] to
the cookie name.
Depending on register_globals, regular PHP variables can be created
from cookies
Here php are some examples:
<?php
echo $_COOKIE["your cookie name"];
?>
<?php
print_r($_COOKIE);
?>
It's not recommended to rely on them as this
feature is often turned off for the sake of security.
http://php.net/manual/en/features.cookies.php
If you already managed to save to cookie in javascript, then it should be no problem to retrive it in PHP, just use $_COOKIE["COKKIE_NAME"] (Where you ofcourse change COOKIE_NAME, to the name of the cookie you saved in JS)..
Have a look at http://php.net/manual/en/features.cookies.php for more examples.

Conditional Cached Page Redirect

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;
}

Set cookie and display in new page

function form()
{
var formVal1=document.forms ["form1"]["num1"].value;
var formVal2=document.forms ["form1"]["num2"].value;
if ( formVal1<1 || formVal1>100)
{
alert("Please enter a value between 1-100");
document.form1.num1.focus() ;
return false;
}
else if ( formVal2<1 || formVal2>100)
{
alert("Please enter a value between 1-100");
document.form1.num2.focus() ;
return false;
}
var sum= ((document.forms ["form1"]["num1"].value - 0 ) + (document.forms ["form1"]["num2"].value - 0));
alert("Sum of two numbers:" +sum);
if(sum>0)
{
var fromVal3=prompt("Please enter the third value:");
if(fromVal3<1 || fromVal3>5)
{
alert("Please enter a value between 1-5");
document.form1.num3.focus() ;
return false;
}
var Mul=fromVal3*sum;
alert("Multiplied Value:" +Mul);
}
if(typeof(Storage)!=="undefined")
{
document.cookie=Mul;
alert(document.cookie);
var allcookies=document.cookie;
document.write(allcookies);
}
else
{
document.getElementById("result").innerHTML="Sorry, your browser does not support web storage...";
}
}
it is a javascipt form hmtl page to take two inputs and prompts for the third and it will multiply with sum of first two numbers and sets the result as cookie and must display the cookie on new page. can anyone help me with setting a cookie and displaying it on new page??
To set javascript cookie you need something like this
document.cookie="username=John";
or
document.cookie="username=Joh"; expires=...; path=...";
So, in your example, it would be something like:
document.cookie='Mul='+Mul;
As far as getting cookies goes, all you have is document.cookie which will look something like a=b; c=d; e=f which means that you need to split few times to get what you need. Something like this:
var c = document.cookie.split('; ');
for (i=0;i<c.length;i++) {
var cookie = c[i].split('=');
if (cookie[0]=='Mul') {
var myCookie = cookie[1];
break;
}
}
After this, you will have your cookie stored in myCookie variable.

Cannot access cookie in javascript

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=/'

Categories