Cookies not being created JS - javascript

When running my web page the cookies are not being created I have been using IE as I know that chrome does not load cookies on local web pages.
I am loading the JS as
<script language="javascript" src="script.js" type="text/javascript"></script>
the script to set the cookies which is in the script.js file is
function SetCookie(name,val) {
document.cookie = name + "=" + val + ';';
}
and in my file for the main page I have set the cookie as shown
SetCookie('July',July);
When I run the code the cookie is undefined.

The simplest way to create a cookie is to assign a string value to the document.cookie object
document.cookie = "key1=value1;key2=value2;expires=date";
So, either July has to be a variable or you'll have to pass it as a string.
var July = 'July';
SetCookie('July', July);
OR
SetCookie('July', 'July');

Related

Reading a cookie with jquery that was set by PHP

I'm trying to set a cookie in PHP, and then have my JavaScript/jQuery read it. As I've been trying to research the issue I've seen some people talk about server side vs. client side cookies, and other people saying cookies are just cookies and there's no difference. What I do know is that PHP sees the cookies, and JavaScript doesn't.
Here's a simplified version of the PHP file that builds the page and sets the cookies.
<!DOCTYPE html>
<?php
setcookie("card", "", time()+900, '/');
?>
<html>
<body>
<?php
$card = "a string I want in my cookie";
$_COOKIE['card'] = $card;
foreach($_COOKIE as $c => $c_value)
{
echo "Cookie named " . $c . " has value " . $c_value . "<br/>";
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery.cookie#1.4.1/jquery.cookie.min.js"></script>
<script type = "text/javascript" src = "script.js"></script>
</body>
</html>
This will correctly show the name and value of the cookie on my page. So I know I'm setting something.
But when my JavaScript runs, I don't seem to have any cookies. I tried a couple different ways to get to the value of either all cookies, or just a single target part of the cookie:
var all_cookies = document.cookie;
var aCard = $.cookie('card');
all_cookies shows up with a value of "" when I debug, and aCard just stays undefined.
So do I need to set the cookies differently with PHP? Or read them differently with either JavaScript or jQuery?
PHP's setcookie() function sets an HTTP response header that instructs the browser to set the cookie. This is only possible if you haven't sent any output yet. Calling setcookie() after you have already output the <!DOCTYPE means you should be getting a "Cannot modify header information - headers already sent" warning.
To set a cookie and make it available to Javascript, you need to set it at the very beginning of your script before generating any output:
<?php
$card = "a string I want in my cookie";
setcookie("card", $card, time()+900, '/');
// note from the manual (https://php.net/setcookie):
// Once the cookies have been set, they can be accessed
// on the next page load with the $_COOKIE array.
// ^^^^^^^^^^^^^^^^^^^^^
//
// so the "card" cookie won't be in $_COOKIE until
// the next page load. If you want it in there
// immediately, you need to set it manually:
$_COOKIE['card'] = $card;
?>
<!DOCTYPE html>
<html>
<body>
<?php
foreach($_COOKIE as $c => $c_value)
{
echo "Cookie named " . $c . " has value " . $c_value . "<br/>";
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery.cookie#1.4.1/jquery.cookie.min.js"></script>
<script type = "text/javascript" src = "script.js"></script>
</body>
</html>
Now that you've used setcookie() before generating any output, the cookie is set properly and Javascript should be able to access it from document.cookie without any trouble.

Adding a cookie in Shopify

I am trying to add a value in cookie in my store. Javascript is not an option because the content of the cookie needs to be invisible on the client-side page source.
In a PHP server it's done using a code like this:
<?php
$cookie_name = "PHPsecret";
$cookie_value = "The secret";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
Can someone please help me acheive this in Shopify? Even if it can be done with some work-around trick such as manipulating the cart attribiute etc. it's okay. Let me know how.
Much appreciated.
I needed to pass a Shopify variable, {{ cart.item_count }} to a subdomain using a cookie. For me, adding this in Javascript at the bottom of theme.liquid did the trick:
<script>
var nowCart = new Date();
var timeCart = nowCart.getTime();
var expireTimeCart = timeCart + 1000*36000;
nowCart.setTime(expireTimeCart); // " + nowCart.toUTCString() + "
document.cookie = "_count={{ cart.item_count }};domain=.example.com;expires=;SameSite=none;Secure=true";
</script>
</body>
</html>
In Shopify Liquid, there is to the best of my knowledge no way to "hide" a cookie. In fact, anyone who knows how to open their dev tools would be able to read your cookie either way...does it really need to stay a secret (consider adding it to a liquid variable instead)?
The next best option I can recommend is to put your Javascript into a separate .js file in the assets folder of your theme.liquid and include it in your theme like so, {{ "cookie-code.js" | asset_url | script_tag }}.
Once again, if the user can open dev tools, they could still read your cookie or look at your javascript file. Maybe clarify in more detail what exactly it is that you're trying to achieve?

Cookie set with javascript, not recognised with PHP (same domain and path)

These are my cookies:
My cookies
I'm running my website from my own computer using a WAMP server. I access my main page from http://127.0.0.1/Zulaijen/, and this is the javascript funcion to set the cookies (User and Session):
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "; expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + expires;
}
When I read them using javascript, it works fine. I get my session. Then I go to another PHP page named 'uploader.php' with this code:
if(!isset($_COOKIE['TestCookie']))
setcookie("TestCookie", "Hello World!", time()+3600);
print_r($_COOKIE);
echo("Session: " . $_COOKIE['Session'] . "<br/>User: " . $_COOKIE['User'] . "<br/>");
And the result is:
Array ( [TestCookie] => Hello World! )
Notice: Undefined index: Session in D:\wamp\www\Zulaijen\uploader.php
on line 30
Notice: Undefined index: User in D:\wamp\www\Zulaijen\uploader.php on line 30
Which means my PHP code is not reading the cookies I set with javascript. It only reads the one I set with my PHP code (TestCookie). And I don't understand why. They are within the same domain and the same path.
You should try setting cookie path. Could be that the cookie paths for PHP and JavaScript isn't matching, hence the cookie will not be shared between the two.
JavaScript cookie path:
How do I set path while saving a cookie value in JavaScript?
PHP coookie path (see path section):
http://php.net/manual/en/function.setcookie.php
I finally found out what was causing the problem (by accident). It's very confusing, but it has a very simple solution.
In order to read the cookies from PHP, you must read them from the very beginning of the file.
Doing this:
<?php print_r($_COOKIE); ?>
At the very beginning of the file (before any HTML code) prints every cookie I set correctly as it should. Even if you set them from PHP, if you don't do it from the very beginning of the file you won't be able to get them.
The reason why I was able to read the one I was setting with PHP was simply because I was setting it right before reading it, or so it seems.

Javascript + characters get removed when alerting encrypted string from cookie

I have an encrypted string in a cookie, the string has been encrypted using CryptoJS. When i look at the cookie with a tool called CookiesManager, the cookie is normal. But when i alert it from the cookie all the + characters have been removed. I am using a jQuery plugin called jQuery Cookie. I have tried to set encoding to UTF-8, but the + characters are still removed.
Code(Js):
<script type="text/javascript" charset="UTF-8">
var host = $.cookie("encrHost");
alert("Host: " + host);
</script>
What gets alerted:
Host: U2FsdGVkX18vi2P/aWBEA4AzwE4 oMDFP2 tucKLyKk=
Cookies Manager Screen Shot:
This is because by default the cookie is url encoded as stated in the plugin homepage:
By default the cookie value is encoded/decoded when writing/reading, using encodeURIComponent/decodeURIComponent. Bypass this by setting raw to true:
$.cookie.raw = true;
So just add $.cookie.raw = true before you call it and you should do the trick.

Set Cookie Path

I have a javascript cookie which works although I have pages in different directories. The cookie set on the default page has a path "/" while the cookie set in another directory has a path "/example"
I know many people have asked this many times but I can't do it by myself. I made a cookie code that actually works from the past three months. I don't want to mess it up. Can anyone help me add a set path "/" to my cookie code? Thanks in advance.
My code is:
<script language="JavaScript">
function SetCookie(cookieName,cookieValue) {
var today = new Date();
var expire = new Date();
var nDays=365
expire.setTime(today.getTime() + 3600000*24*nDays);
document.cookie = cookieName+"="+escape(cookieValue)
+ ";expires="+expire.toGMTString();
}
</script>
Indicate the path by adding the following to the end of the cookie string in function "SetCookie":
"; path=/";
http://www.quirksmode.org/js/cookies.html#doccookie

Categories

Resources