I have cookie name like cookiemyname and its value.
How to pass such value into Javascript as variable in the correct way?
document.cookie = "key=value";
That is a proper way.
Other info that follows the value is semicolon-separated and optional, and details about them can be found at the Document.cookie documentation page.
As we know PHP is a server side script and JavaScript runs in the browser and whether the cookie originates in JS or PHP should not matter in this case. Cookies are stored in the document.cookie JavaScript object which in our browser currently holds the following name/value pairs:setUserId/XXXYYYYZZZ123
Which Javascript script is the easiest to do this as cookie is already stored and it has name like and value XXXYYYYZZZ123?
I have to pass value of the user into
_paq.push([‘setUserId’, ‘XXXYYYYZZZ123’]);
There are a ton of functions online to read cookies in JS.
https://www.google.com/search?q=read+cookie+javascript
Here’s one:
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 "";
}
Use like so:
document.cookie = "setUserId=XXXYYYYZZZ123";
> "setUserId=XXXYYYYZZZ123"
getCookie("setUserId");
> "XXXYYYYZZZ123"
I’m new to this.
Thank you for your reply. I see document.cookie
Will this work to retrieve specific cookie from my browser?
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 "";
}
getCookie('mycookie_name');
document.cookie = "cookie_value";
document.cookie is to set a cookie.
The getCookie function is to retrieve a specific cookie.
So, if I use cookie function it will retrieve cookie value for the specific cookie name using getCookie(‘mycookie_name’);?
How to store into variable in this case?
I have to store into variable and this line:
_paq.push([‘setUserId’, ‘cookie_value’]);
Yup.
var userId = getCookie("setUserId");
paq.push([‘setUserId’, userId]);
Or just:
paq.push([‘setUserId’, getCookie("setUserId")]);
I have tested. This code works perfect. Thank you for all help. I have to test if there are any open issues.
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.