Javascript - Issue with caching and cookies - javascript

I am getting quite a frustrating issue with JavaScript and Cookies on cached pages.
I got the following JS code:
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 "";
}
if (!getCookie("lang") == "{{Lang}}"){
document.reload();
}
{{Lang}} is replaced with the very same cookie on the backend with PHP.
$template = str_replace("{{Lang}}", $lang, $template);
But that is not really relevant since that part works as intended.
The issue is that when the user visits a cached page.
The JS previously mentioned becomes
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 "";
}
if (!getCookie("lang") == "FR"){
document.reload();
}
The issue is that the page does not refresh even though the Chrome Dev tools quite clearly say that the cookie lang is set to "EN", not "FR".
Is there a method around this caching issue?

The not equal comparison in JS is !=, so
getCookie("lang") != "FR"

The reload method accepts a Boolean flag indicating a force cache refresh. So try:
document.reload(true);

Related

getting cookie info but nothing works

// Set COOKIE
$cookie_name = 'domain[user]';
$cookie_value = 'domain[id]';
// Cookie need to change right away after user press login
setcookie($cookie_name,$sub_name,time()+(60*60*24),'/');
setcookie($cookie_value,$auth_id,time()+(60*60*24),'/');
// Forced cookie to exit after set
$_COOKIE['domain']['user'] = $sub_name;
$_COOKIE['domain']['id'] = $auth_id;
I am setting my domain name like this on php , but I want to fetch it by JavaScript or jquery, but I have problem getting them.
here is what I have tried.
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;
}
var value = readCookie('domain["user"]');
alert(value);
how do I get the my cookie info?
You have to decode the cookie before parsing it.
Try this:
function readCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
//var decodedCookie = "fbm_229931260731834=base_domain=.chris01.com; fblo_229931260731834=y; PHPSESSID=f1djg4brueiqkkqnkjiqj6s5q0; domain[user]=admin; domain[authID]=ba981df7c9aa72ad461461ad524cca01049938f8869098b31065058e7fdaa7e65e3072f637d43c10ba51a5cd6f5ec77d0ccf4befc066320c686168d7638b57e3";
var ca = decodedCookie.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 value = readCookie("domain[user]");
alert(value);
Please consider do not call the cookie name like this: readCookie('domain["user"]');
You have to call it like this: readCookie("domain[user]");

Manage special character in cookie

I have this function to retrieve cookie in javascript
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 "";
}
Usually it works fine but I tried this function with a cookie storing an email address.
Each time the function run, the cookie is deformed. See the result of the following code:
setInterval( test, 5000 );
function test(){
var email = getCookie('email');
console.log(email);
}
Result :
test#test.eu //At start
test%2540test.eu //After 5s
test%252540test.eu //After 10s
test%25252540test.eu
test%2525252540test.eu
test%252525252540test.eu
Why speical char such as '#' are misinterpreted ?
If your first getCookie returns the correct data then you should check the function which modifies the data between intervals.
There is your problem.

Write cookie in ashx file

i try write new cookie in ashx file,but i get error
HttpCookie cookname;
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i];
string filename = "~/img/" + "111" + file.FileName;
filenames.Add(filename);
file.SaveAs(context.Server.MapPath(filename));
cookname["filename"] = filename;
Response.Cookies.Add(cookname);
}
And how i can get cookie in javascript?
Thank
You have to initialize HttpCookie first with a name like
HttpCookie cookName = new HttpCookie("yourCookieName");
Then add value whatever you want like
cookName["yourPropertyName"] = value;
To get cookie in javascript, you can use following function
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 "";
}
Then call the function to get cookie like
getCookie("yourCookieName=yourPropertyName")

Retrieve jQuery Cookie value

Example, I have this cookie:
$.cookie("foo", "500", { path: '/', expires: 365 });
How do I get the value of that cookie and put it into a variable?
For example (I know this is not correct):
var foo = $.cookie("foo").val();
It's just var foo = $.cookie("foo").
There's no need for a .val() call as you're not accessing the value of a DOM element.
This worked for me
function getCookieValue(cname) { // cname is nothing but the cookie value which
//contains the value
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.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 "";
}
To get the value of a cookie, you can just call it's reference. For example:
$.cookie("foo", "somevalue");
alert($.cookie("foo"));
Will alert:
somevalue
By this way we can access
console.log($.cookie()); //It will gives the all cookies in the form of object
alert($.cookie('foo'));//it will give cookie foo value ie 500

Javascript Cookie problems IE

been bagging my head over some Javascript, please help, I cant see why it simply wont find my cookie in IE 7 or 8
I am setting the cookie true through another event, but I just want to see IE pick up the cookie which I initially set. Works in firefox too, thanks in advance.
var t=setTimeout("doAlert()",8000);
var doAlertVar = true;
document.cookie = "closed=0;expires=0;path=";
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie;
alert(ca);
ca = ca.replace(/^\s*|\s*$/g,'');
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 doAlert(){
if(readCookie('closed')==1){
doAlertVar = false;
}
if(readCookie('closed')==0){
alert("unlicensed demo version\nbuy online at");
}
t=setTimeout("doAlert()",5000);
}
Where to begin..
setTimeout("doAlert()",8000);
// do not use strings as an argument to setTimeout, that runs eval under the hood.
// use
setTimeout(doAlert,8000);
// instead
document.cookie = "closed=0;expires=0;path=";
// this is wrong, expires should follow the format Fri, 14 May 2010 17:22:33 GMT (new Date().toUTCString())
// path should be path=/
You can also do this with a regex:
function readCookie(name, defaultValue) {
var value = defaultValue;
document.cookie.replace(new RegExp("\\b" + name + "=([^;]*)"), function(_, v) {
value = v;
});
return value;
}

Categories

Resources