Inserting cookie value into hidden fields - javascript

I'm having trouble getting two cookie values and adding them to a form field on my website. Below is the script I've added, which also populates the values in JavsScript Console; however I can't get the cookie values into the form fields.
Form fields:
<input type="text" id="usource" name="usource" value="">
<input type="text" id="referrer" name="referrer" value="">
I've tried this JS to populate the "usource" and "referrer" field, but it doesn't seem to work. Am I missing something?
document.getElementById("usource").value = utmCookie.utm_source;
document.getElementById("referrer").value = utmCookie.referrer;
This is the script I'm using which saves UTM parameters in cookies whenever there are any UTM parameters in the URL. It also saves the initial referrer information in a cookie which is ever (365 days) overwritten.
var utmCookie = {
cookieNamePrefix: "",
utmParams: [
"utm_source",
"utm_medium",
"utm_campaign",
"utm_term",
"utm_content"
],
cookieExpiryDays: 365,
// From http://www.quirksmode.org/js/cookies.html
createCookie: function (name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
} else
var expires = "";
document.cookie = this.cookieNamePrefix + name + "=" + value + expires + "; domain=.mywebsite.com; path=/";
},
readCookie: function (name) {
var nameEQ = this.cookieNamePrefix + 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;
},
eraseCookie: function (name) {
this.createCookie(name, "", -1);
},
getParameterByName: function (name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
console.log(name);
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if (results == null) {
return "";
} else {
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
},
utmPresentInUrl: function () {
var present = false;
for (var i = 0; i < this.utmParams.length; i++) {
var param = this.utmParams[i];
var value = this.getParameterByName(param);
console.log(param + ' = ' + value);
if (value != "" && value != undefined) {
present = true;
}
}
return present;
},
writeUtmCookieFromParams: function () {
for (var i = 0; i < this.utmParams.length; i++) {
var param = this.utmParams[i];
var value = this.getParameterByName(param);
this.writeCookieOnce(param, value)
}
},
writeCookieOnce: function (name, value) {
var existingValue = this.readCookie(name);
if (!existingValue) {
this.createCookie(name, value, this.cookieExpiryDays);
}
},
writeReferrerOnce: function () {
value = document.referrer;
if (value === "" || value === undefined) {
this.writeCookieOnce("referrer", "direct");
} else {
this.writeCookieOnce("referrer", value);
}
},
referrer: function () {
return this.readCookie("referrer");
}
};
utmCookie.writeReferrerOnce();
if (utmCookie.utmPresentInUrl()) {
utmCookie.writeUtmCookieFromParams();
}

Related

Multiple name capture from sign up form

I had some code created to convert a 3rd party form to jQuery AJAX with a custom redirect. On the redirect page the users name from the form was captured. The issue is that I can only capture the name once. If I try to duplicate the code to show the name multiple times it doesn't work.
Would much appreciate the help!
------Javascript for the submit button------
window.CFS = window.CFS || {};
(function () {
"use strict";
CFS.msgPleaseWait = 'Please wait...';
CFS.msgRedirect = 'Redirecting...';
CFS.nameField = '';
CFS.nameFromSubmitField = '';
CFS.redirectTo = '';
CFS.submitButtonText = '';
CFS.submitHandler = function(form) {
var $form = $(form);
var dataToPost = $form.serialize();
var urlToPostTo = $form.attr("action");
var $submitButton = $("input[type='submit']", $form);
CFS.submitButtonText = $submitButton.val();
CFS.disableSubmit($submitButton);
$.ajax({
type: 'POST',
url: urlToPostTo,
data: dataToPost,
success: function(data) {
if (CFS.redirectTo) {
$submitButton.val(CFS.msgRedirect);
if (CFS.nameField) {
var nameFieldVal = '';
if ($("input[name='" + CFS.nameField + "']", $form)) {
nameFieldVal = $("input[name='" + CFS.nameField + "']", $form).val();
}
if (nameFieldVal) {
CFS.setCookie('name', nameFieldVal, 60);
}
}
window.location.replace(CFS.redirectTo);
} else {
CFS.enableSubmit($submitButton);
}
},
error: function() {
console.log('Campaigner.com error!');
CFS.enableSubmit($submitButton);
}
});
}
CFS.disableSubmit = function($button) {
$button.attr("disabled", "disabled");
$button.val(CFS.msgPleaseWait);
}
CFS.enableSubmit = function($button) {
$button.val(CFS.submitButtonText);
$button.removeAttr("disabled");
}
CFS.setCookie = function(name, value, seconds) {
var d = new Date();
d.setTime(d.getTime() + (seconds * 1000));
var expires = 'expires=' + d.toUTCString();
document.cookie = name + '=' + value + ';' + expires + ';path=/';
}
CFS.getCookie = function(name) {
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);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return '';
}
CFS.setNameFromSubmit = function() {
if (CFS.nameFromSubmitField) {
var elem = document.getElementById(CFS.nameFromSubmitField);
var savedName = CFS.getCookie('name');
if (elem && savedName) {
elem.innerHTML = savedName;
}
}
}
})();
------Name Field Captured-----
<p>Hello my name is <span id="nameFromSubmit">NAME HERE</span>
<script src="custom-submit.js" type="text/javascript"></script>
<script type="text/javascript">
if ((typeof CFS !== 'undefined') && CFS.setNameFromSubmit) {
CFS.nameFromSubmitField = 'nameFromSubmit';
CFS.setNameFromSubmit();
}
</script>

Making javascript counter stop

I have this counter:
http://codepen.io/leticiamartinch/pen/YpJgqx
Here is the code:
var MAX_COUNTER = 1000000;
var counter = null;
var counter_interval = null;
var deadline = localStorage.deadline;
function setCookie(name,value,days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires="+date.toGMTString();
}
else {
expires = "";
}
document.cookie = name+"="+value+expires+"; path=/";
}
function getCookie(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 deleteCookie(name) {
setCookie(name,"",-1);
}
function resetCounter() {
counter = MAX_COUNTER;
}
function stopCounter() {
window.clearInterval(counter_interval);
deleteCookie('counter');
}
function updateCounter() {
var msg = '';
if (counter > 0) {
counter -= 1;
msg = counter;
setCookie('counter', counter, 1);
}
else {
msg = "Counting finished.";
stopCounter();
}
var el = document.getElementById('counter');
if (el) {
el.innerHTML = msg;
}
}
function startCounter() {
stopCounter();
counter_interval = window.setInterval(updateCounter, 1000);
}
function init() {
counter = getCookie('counter');
if (!counter) {
resetCounter();
}
startCounter();
}
init();
I'd like it to decrease in a slower basis so that it doesn't seems to be a timer countdown but full number counter.
Let me guess that you want it to look like e.g. a download counter which has real underlying data instead of a timed counter where people can see that it is just an artificial countdown.
I'd suggest to generate two random numbers - one for the next time interval till decrease and one for the amount of decrease. Set the time interval to be random between - let's say 1 and 3 and the amount between 1 and 5 (depending on how fast you want the countdown to be). You probably want to experiment with the values. Also don't set an initial value of 1000000 because that looks rather obviously fake.
Such an implementation could make sense for example when creating a mockup for a customer where you later put the real underlying data, such that your customer gets a feeling on how the counter will behave later.
If I'm guessing wrongly on what you initially want - please let us know and provide more information.
Here is what you'll get:
var MAX_COUNTER = 1294652;
var counter = null;
var counter_interval = null;
var deadline = localStorage.deadline;
function setCookie(name,value,days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires="+date.toGMTString();
}
else {
expires = "";
}
document.cookie = name+"="+value+expires+"; path=/";
}
function getCookie(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 deleteCookie(name) {
setCookie(name,"",-1);
}
function resetCounter() {
counter = MAX_COUNTER;
}
function stopCounter() {
window.clearInterval(counter_interval);
deleteCookie('counter');
}
function updateCounter() {
var msg = '';
if (counter > 0) {
newDecreaseAmount = Math.floor(Math.random() * 3) + 1;
counter -= newDecreaseAmount;
msg = counter;
setCookie('counter', counter, 1);
// set new interval
newInterval = (Math.floor(Math.random() * 5) + 1) * 1000;
counter_interval = window.setTimeout(updateCounter, newInterval);
}
else {
msg = "Counting finished.";
stopCounter();
}
var el = document.getElementById('counter');
if (el) {
el.innerHTML = msg;
}
}
function startCounter() {
stopCounter();
updateCounter();
}
function init() {
counter = getCookie('counter');
if (!counter) {
resetCounter();
}
startCounter();
}
init();

Cannot get value of certain cookies - Javascript

I have been using this code found on Github to collect some UTM/other URL parameters.
I have been able to successfully save the parameters in a cookie, and pass those values into a hidden input form.
This code is loaded through Google Tag Manager on every page of the website.
Scenario:
-The cookie sessions exist on every page of the site as expected.
-The main website is on a non-secure HTTP connection (http://www.example.com).
-A secure page exists on the subdomain. (https://www.subdomain.example.com).
Problem: On the secure, subdomain page, I cannot get the values from none of the UTM cookies. I can get the values from the VISITORS, IREFERRER, LREFERRER, and ILANDINGPAGE cookies, but not from the UTM cookies.
Here is the code that I am using:
<script type="text/javascript" charset="utf-8">
jQuery(document).ready(function(){
var _uf = _uf || {};
_uf.domain = ".exampledomain.com";
var UtmCookie;
UtmCookie = (function() {
function UtmCookie(options) {
if (options == null) {
options = {};
}
this._cookieNamePrefix = '_uc_';
this._domain = options.domain;
this._sessionLength = options.sessionLength || 1;
this._cookieExpiryDays = options.cookieExpiryDays || 365;
this._additionalParams = options.additionalParams || [];
this._utmParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content'];
this.writeInitialReferrer();
this.writeLastReferrer();
this.writeInitialLandingPageUrl();
this.setCurrentSession();
if (this.additionalParamsPresentInUrl()) {
this.writeAdditionalParams();
}
if (this.utmPresentInUrl()) {
this.writeUtmCookieFromParams();
}
return;
}
UtmCookie.prototype.createCookie = function(name, value, days, path, domain, secure) {
var cookieDomain, cookieExpire, cookiePath, cookieSecure, date, expireDate;
expireDate = null;
if (days) {
date = new Date;
date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
expireDate = date;
}
cookieExpire = expireDate != null ? '; expires=' + expireDate.toGMTString() : '';
cookiePath = path != null ? '; path=' + path : '; path=/';
cookieDomain = domain != null ? '; domain=' + domain : '';
cookieSecure = secure != null ? '; secure' : '';
document.cookie = this._cookieNamePrefix + name + '=' + escape(value) + cookieExpire + cookiePath + cookieDomain + cookieSecure;
};
UtmCookie.prototype.readCookie = function(name) {
var c, ca, i, nameEQ;
nameEQ = this._cookieNamePrefix + name + '=';
ca = document.cookie.split(';');
i = 0;
while (i < ca.length) {
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);
}
i++;
}
return null;
};
UtmCookie.prototype.eraseCookie = function(name) {
this.createCookie(name, '', -1, null, this._domain);
};
UtmCookie.prototype.getParameterByName = function(name) {
var regex, regexS, results;
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
regexS = '[\\?&]' + name + '=([^&#]*)';
regex = new RegExp(regexS);
results = regex.exec(window.location.search);
if (results) {
return decodeURIComponent(results[1].replace(/\+/g, ' '));
} else {
return '';
}
};
UtmCookie.prototype.additionalParamsPresentInUrl = function() {
var j, len, param, ref;
ref = this._additionalParams;
for (j = 0, len = ref.length; j < len; j++) {
param = ref[j];
if (this.getParameterByName(param)) {
return true;
}
}
return false;
};
UtmCookie.prototype.utmPresentInUrl = function() {
var j, len, param, ref;
ref = this._utmParams;
for (j = 0, len = ref.length; j < len; j++) {
param = ref[j];
if (this.getParameterByName(param)) {
return true;
}
}
return false;
};
UtmCookie.prototype.writeCookie = function(name, value) {
this.createCookie(name, value, this._cookieExpiryDays, null, this._domain);
};
UtmCookie.prototype.writeAdditionalParams = function() {
var j, len, param, ref, value;
ref = this._additionalParams;
for (j = 0, len = ref.length; j < len; j++) {
param = ref[j];
value = this.getParameterByName(param);
this.writeCookie(param, value);
}
};
UtmCookie.prototype.writeUtmCookieFromParams = function() {
var j, len, param, ref, value;
ref = this._utmParams;
for (j = 0, len = ref.length; j < len; j++) {
param = ref[j];
value = this.getParameterByName(param);
this.writeCookie(param, value);
}
};
UtmCookie.prototype.writeCookieOnce = function(name, value) {
var existingValue;
existingValue = this.readCookie(name);
if (!existingValue) {
this.writeCookie(name, value);
}
};
UtmCookie.prototype._sameDomainReferrer = function(referrer) {
var hostname;
hostname = document.location.hostname;
return referrer.indexOf(this._domain) > -1 || referrer.indexOf(hostname) > -1;
};
UtmCookie.prototype._isInvalidReferrer = function(referrer) {
return referrer === '' || referrer === void 0;
};
UtmCookie.prototype.writeInitialReferrer = function() {
var value;
value = document.referrer;
if (this._isInvalidReferrer(value)) {
value = 'direct';
}
this.writeCookieOnce('referrer', value);
};
UtmCookie.prototype.writeLastReferrer = function() {
var value;
value = document.referrer;
if (!this._sameDomainReferrer(value)) {
if (this._isInvalidReferrer(value)) {
value = 'direct';
}
this.writeCookie('last_referrer', value);
}
};
UtmCookie.prototype.writeInitialLandingPageUrl = function() {
var value;
value = this.cleanUrl();
if (value) {
this.writeCookieOnce('initial_landing_page', value);
}
};
UtmCookie.prototype.initialReferrer = function() {
return this.readCookie('referrer');
};
UtmCookie.prototype.lastReferrer = function() {
return this.readCookie('last_referrer');
};
UtmCookie.prototype.initialLandingPageUrl = function() {
return this.readCookie('initial_landing_page');
};
UtmCookie.prototype.incrementVisitCount = function() {
var cookieName, existingValue, newValue;
cookieName = 'visits';
existingValue = parseInt(this.readCookie(cookieName), 10);
newValue = 1;
if (isNaN(existingValue)) {
newValue = 1;
} else {
newValue = existingValue + 1;
}
this.writeCookie(cookieName, newValue);
};
UtmCookie.prototype.visits = function() {
return this.readCookie('visits');
};
UtmCookie.prototype.setCurrentSession = function() {
var cookieName, existingValue;
cookieName = 'current_session';
existingValue = this.readCookie(cookieName);
if (!existingValue) {
this.createCookie(cookieName, 'true', this._sessionLength / 24, null, this._domain);
this.incrementVisitCount();
}
};
UtmCookie.prototype.cleanUrl = function() {
var cleanSearch;
cleanSearch = window.location.search.replace(/utm_[^&]+&?/g, '').replace(/&$/, '').replace(/^\?$/, '');
return window.location.origin + window.location.pathname + cleanSearch + window.location.hash;
};
return UtmCookie;
})();
var UtmForm, _uf;
UtmForm = (function() {
function UtmForm(options) {
if (options == null) {
options = {};
}
this._utmParamsMap = {};
this._utmParamsMap.utm_source = options.utm_source_field || 'USOURCE';
this._utmParamsMap.utm_medium = options.utm_medium_field || 'UMEDIUM';
this._utmParamsMap.utm_campaign = options.utm_campaign_field || 'UCAMPAIGN';
this._utmParamsMap.utm_content = options.utm_content_field || 'UCONTENT';
this._utmParamsMap.utm_term = options.utm_term_field || 'UTERM';
this._additionalParamsMap = options.additional_params_map || {};
this._initialReferrerField = options.initial_referrer_field || 'IREFERRER';
this._lastReferrerField = options.last_referrer_field || 'LREFERRER';
this._initialLandingPageField = options.initial_landing_page_field || 'ILANDPAGE';
this._visitsField = options.visits_field || 'VISITS';
this._addToForm = options.add_to_form || 'all';
this._formQuerySelector = options.form_query_selector || 'form';
this.utmCookie = new UtmCookie({
domain: options.domain,
sessionLength: options.sessionLength,
cookieExpiryDays: options.cookieExpiryDays,
additionalParams: Object.getOwnPropertyNames(this._additionalParamsMap)
});
if (this._addToForm !== 'none') {
this.addAllFields();
}
}
UtmForm.prototype.addAllFields = function() {
var fieldName, param, ref, ref1;
ref = this._utmParamsMap;
for (param in ref) {
fieldName = ref[param];
this.addFormElem(fieldName, this.utmCookie.readCookie(param));
}
ref1 = this._additionalParamsMap;
for (param in ref1) {
fieldName = ref1[param];
this.addFormElem(fieldName, this.utmCookie.readCookie(param));
}
this.addFormElem(this._initialReferrerField, this.utmCookie.initialReferrer());
this.addFormElem(this._lastReferrerField, this.utmCookie.lastReferrer());
this.addFormElem(this._initialLandingPageField, this.utmCookie.initialLandingPageUrl());
this.addFormElem(this._visitsField, this.utmCookie.visits());
};
UtmForm.prototype.addFormElem = function(fieldName, fieldValue) {
var allForms, firstForm, form, i, len;
if (fieldValue) {
allForms = document.querySelectorAll(this._formQuerySelector);
if (allForms.length > 0) {
if (this._addToForm === 'first') {
firstForm = allForms[0];
firstForm.insertBefore(this.getFieldEl(fieldName, fieldValue), firstForm.firstChild);
} else {
for (i = 0, len = allForms.length; i < len; i++) {
form = allForms[i];
form.insertBefore(this.getFieldEl(fieldName, fieldValue), form.firstChild);
}
}
}
}
};
UtmForm.prototype.getFieldEl = function(fieldName, fieldValue) {
var fieldEl;
fieldEl = document.createElement('input');
fieldEl.type = "hidden";
fieldEl.name = fieldName;
fieldEl.value = fieldValue;
return fieldEl;
};
return UtmForm;
})();
_uf = window._uf || {};
window.UtmForm = new UtmForm(_uf);
/*
var USOURCE = jQuery("input[name='USOURCE']").val();
var UMEDIUM = jQuery("input[name='UMEDIUM']").val();
var UCAMPAIGN = jQuery("input[name='UCAMPAIGN']").val();
var UCONTENT = jQuery("input[name='UCONTENT']").val();
var UTERM = jQuery("input[name='UTERM']").val();
var IREFERRER = jQuery("input[name='IREFERRER']").val();
var LREFERRER = jQuery("input[name='LREFERRER']").val();
var ILANDPAGE = jQuery("input[name='ILANDPAGE']").val();
var VISITS = jQuery("input[name='VISITS']").val();
console.log(USOURCE);
console.log(UMEDIUM);
console.log(UCAMPAIGN);
console.log(VISITS);
*/
jQuery('#saveProfile').on('click', function(e){
console.log('Click submitted');
e.preventDefault();
// Original JavaScript code by Chirp Internet: www.chirp.com.au
// Please acknowledge use of this code by including this header.
function getCookie(cname) {
var name = cname + "=";
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);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length,c.length);
}
}
return "";
}
var readCampaign = readCookie_uc_utm_campaign
var FirstName = jQuery('#ownerInformation_FirstName').val();
var LastName = jQuery('#ownerInformation_LastName').val();
var USOURCE = getCookie('_uc_utm_source');
console.log(USOURCE);
var UMEDIUM = getCookie('_uc_utm_medium') || '';
var UCAMPAIGN = getCookie('_uc_utm_campaign') || '';
var UCONTENT = getCookie('_uc_utm_content') || '';
var UTERM = getCookie('_uc_utm_term') || '';
var IREFERRER = jQuery("input[name='IREFERRER']").val();
var LREFERRER = jQuery("input[name='LREFERRER']").val();
var ILANDPAGE = jQuery("input[name='ILANDPAGE']").val();
var VISITS = jQuery("input[name='VISITS']").val();
dataLayer.push({'event':FirstName,'event_cat':LastName,'event_action':USOURCE,'event_label':VISITS});
jQuery.ajax({
url: "https://script.google.com/macros/s/googleappsscript/exec",
data: {'FirstName':FirstName,'LastName':LastName,'USOURCE':USOURCE, 'UMEDIUM':UMEDIUM, 'UCAMPAIGN':UCAMPAIGN, 'UCONTENT':UCONTENT, 'UTERM':UTERM, 'IREFERRER':IREFERRER, 'LREFERRER':LREFERRER, 'VISITS':VISITS},
type: "POST",
dataType: "json"
});
});
})
</script>
Any help or guidance would be greatly appreciated.
Thanks,
Blaine
The reason why cookies are restricted by domains like this is to prevent security breaches.
See this answer for the way around it: Cross-Domain Cookies

Cookie is not deleting properly using jquery

I have a task to set the cookie for the menu.I have a horizontal menu.When I click on the menu the id of the menu is set in to the cookie.But when I am selecting the next menu cookie shows the first input value.For that I used $.removeCookie("activeDivId");.But it doesn't work properly.How can I solve this problem?
Html code is
<div class="menuBar">
<div id="divHome" class="menuHeader ui-corner-top">
<span>Home</span>
</div>
<div id="divNewTransaction" class="menuHeader ui-corner-top">
<span><a href="#" onclick="NewTransaction()" >New Transaction</a></span>
</div>
</div>
javascript file is
$(document).ready(function () {
$(".menuHeader").click(function () {
$.removeCookie("activeDivId");
$.cookie("activeDivId", this.id); });
alert(document.cookie);
var activeDivId = $.cookie("activeDivId") ? $.cookie("activeDivId") : "divHome";
$("#" + activeDivId).addClass("menuHeaderActive");
});
$(document).ready(function () {
//for debugging purpose, so that you can see what is in the menu cookie
$('#debug').html('Cookie Content : ' + readCookie('menu'));
//if cookie menu exists
if (readCookie('menu')) {
//loop through the menu item
$('#menu a').each(function () {
//match the correct link and add selected class to it
if ($(this).html() == readCookie('menu')) $(this).addClass('selected');
});
}
$('#menu a').click(function () {
//Set the cookie according to the text in the link
createCookie('menu', $(this).html(),1);
});
});
/* Cookie Function */
function createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; 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);
}
You Can Use this method instead of jquery Method
function createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else var expires = "";
//var fixedName = '';
/// name =name;
document.cookie = name + "=" + value + expires + "; path=/";
this[name] = 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 c;
}
function eraseCookie(cookiename) {
this.createCookie(cookiename, '', -1);
this[cookiename] = undefined;
// Ecookie(cookiename);
}

remember cookie

i want to make a cokkie which can save my selected region on netsoltech.com whenever user select the region on map it can save the cookie and when the next time user come on domain the automatic go to 1st time click region page i make this code
but the problem is when the user come on next time then 1st region selector page come then it can refresh and go to the region page.. not the automatic...
<script>
/*
Cookie script - Scott Andrew
Popup script, Copyright 2005, Sandeep Gangadharan
*/
function newCookie(name,value,days) {
var days = 10; // the number at the left reflects the number of days for the cookie to last
// modify it according to your needs
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString(); }
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/"; }
function readCookie(name) {
var nameSG = name + "=";
var nuller = '';
if (document.cookie.indexOf(nameSG) == -1)
return nuller;
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(nameSG) == 0) return c.substring(nameSG.length,c.length); }
return null; }
function eraseCookie(name) {
newCookie(name,"",1); }
function toMem(region) {
newCookie('region', region);
window.location= "http://www.netsoltech.com/"+region+"/index";
}
function remCookie() {
window.location= "http://www.netsoltech.com/"+readCookie("region")+"/index";
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(function() {
remCookie();
});
</script>
Try this
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
//redirect here
}
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
function checkCookie() {
var region = getCookie("region");
if (region != null && region != "") {
alert("redirect to " + region); //replace this with redirect
}
}
checkCookie(); //check this on page load
and the HTML
europe
JSFiddle
http://jsfiddle.net/YtF2B/6/

Categories

Resources