how to capture part of data from cookie in javascript - javascript

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']

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")

parsing cookie values to if/elseif in javascript

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.')

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

Categories

Resources