So I have a simple session cookie retriever and am writing the cookie values to the page. There are only two values, "Yes" and "No", otherwise it returns null. Currently, it checks if there is a value, and if so, writes that value to the page. How do I tell the script to write the value conditionally (i.e., writing "Yes" because the value was "Yes", same for "No", instead of just passing the response along) instead of if it exists or not?
<script>
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;
};
</script>
...
<p>
Response 1:
<script>
var res1 = readCookie('res1')
if (res1) {
document.write('res1')
}
else {
document.write("You did not respond.")
};
</script>
</p>
function getCookie(name) {
var matches = document.cookie.match(new RegExp(
"(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
))
return matches ? decodeURIComponent(matches[1]) : undefined
}
document.write(getCookie('res1') != undefined ? 'res1' : 'You did not respond.')
Related
I have a cookie on login to a webpage. HEre are the details of the cookie
"{"XXVCode":"T937848","PName":"Garneriere","PAddress":"Dublin 8, southgate","Participation":false,"Coding":true}"
i need to capture XXVCode in a variable how could I do this in javascript on this webpage?
Method 1:
You can use getCookie() function:
// Code collected from w3schools.com
function getCookie(cname) {
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 "";
}
Then you can call:
getCookie('XXVCode');
Method 2:
Note: your cookie string wrapped with double quote, it should be wrapped with single quote.
Because double quote inside double quote will show syntax error.
var cookie = '{"XXVCode":"T937848","PName":"Garneriere","PAddress":"Dublin 8, southgate","Participation":false,"Coding":true}';
var cookieArray = JSON.parse(cookie)
const XXVCode = cookieArray['XXVCode'];
convert to object, and then access key
const cookie = "{"XXVCode":"T937848","PName":"Garneriere","PAddress":"Dublin 8, southgate","Participation":false,"Coding":true}"
const cookieJSON = JSON.parse(cookie)
const XXVCode = cookieJSON['XXVCode']
// 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]");
I have this script in JS
function setCookie(name, value, days) {
var d = new Date;
d.setTime(d.getTime() + 24*60*60*1000*days);
document.cookie = name + "=" + value + ";path=/;expires=" + d.toGMTString();
}
I can see in my Chrome browser options->settings that the cookie name "workLocation" is set. The domain for the cookie is "/", 'send for' option is "Any kind of Connection" and 'accessible to script' option is "Yes".
when I call the cookie using JS code below, it returns null.
function getCookie(name) {
var v = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
return v ? v[2] : null;
}
alert(getCookie("workLocation"));
I had tried using PHP to show cookies var_dump($_COOKIE); but it only shows codeigniter cookies "ci_session" and "httpUser". I had used the same javascript to set and get cookies and it's working, except for this page. Any ideas how to solve it?
cookie in server and in client is different the cookie in server is stored in
Local Storage
and the cookie in client is stored in
Cookies
if you want to get the cookie from js u can use this functions :
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 "";
}
function checkCookie() {
var user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
setCookie("username", user, 365);
}
}
}
but if you want to get the cookie from php especially those session in CI
u can use this command $this->session->userdata("key");
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.
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