JS equivalent of PHP function to find cookies - javascript

I have a small shopping cart to use with PHP in WordPress, but now I'm implementing it to be used in a site with AJAX.
I have a PHP function that finds some cookies that tell me what the user has put in the shopping cart, however, since now I'm loading the product info into the same div according to user selection, that function with PHP is no longer useful and need to do it with JS or JQuery in order to be updated every time the user changes to another product.
The function in PHP is:
function in_cart($post_id){
$found = false;
if(!empty($_COOKIE['cart'])){
foreach ($_COOKIE ['cart'] as $c) {
if ($c ['id'] == $post_id)
$found = $c;
}
}
return $found;
}
The cookies are called "cart[0][id]" and "cart[0][quantity]" where the "0" increments depending on how many products there are, and with that function I can just run trough all instances of a cookie that starts as "cart", but I can't seem to replicate that loop in JS.
I tried to do it with a regex expression in order to allow any number inside the first set og brackets, but it won't work (I'm quite new to JS so not sure if I did it correctly).
Does anyone have a suggestion?
UPDATE:
This was my last attempt to use regex:
var nums = /^[0-9]+$/;
function readCookie(c_name)
{
var c_value = document.cookie;
var c_start = c_value.indexOf(" " + c_name + "=");
if (c_start == -1)
{
c_start = c_value.indexOf(c_name + "=");
}
if (c_start == -1)
{
c_value = null;
}
else
{
c_start = c_value.indexOf("=", c_start) + 1;
var c_end = c_value.indexOf(";", c_start);
if (c_end == -1)
{
c_end = c_value.length;
}
c_value = unescape(c_value.substring(c_start,c_end));
}
return c_value;
}
cart = readCookie("cart["+ nums +"][id]");

Please see the excellent MDN article on how to access cookies in javascript, they even provide a full implementation for reading/writing cookie values. In a nutshell, cookies can be accessed as attribute of the document: document.cookie. That attribute has all the cookies belonging to your domain stored as string (e.g.: foo=bar;baz=bizz). To access an individual element you would have to come up with some regex magic, thus the link to the MDN article. ;-)
The solution there let's you set/get/check/delete cookies very comfortable, e.g.
docCookies.setItem("foo", "bar");
docCookies.getItem("foo"); // bar
docCookies.hasItem("foo"); // true
docCookies.removeItem("foo");
Btw, if you're using jQuery, there's a very nice plugin.

Related

Reading cookie value does only work sometimes

at first i want to make a short description of the process containing the problem:
If someone clicks one of our company's AdWords ads and comes on our website i'm creating a cookie "adwords" with the value "true" via Google Tag Manager (Trigger: URL contains "?gclid="). The cookie is only set with "true", a cookie with "false" is not created at any point.
Then, when someone clicks on our contact form link, i read the value from the "adwords"-cookie and pass it into a blind field in the contact form. When the user clicks the "send" button, i get an email containing his data including the cookie value.
Everytime i try it myself it works perfectly. But when i compare the number of conversions in my AdWords-account with the data i get from my contact form it seems to be working only sometimes for other users.
I'm a beginner in javascript so maybe theres a error in reasoning in my script (its mostly from w3schools):
function getAdwordsCookie(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 "false";
}
function SetAdwordsField() {
proforms.setValue(21,getAdwordsCookie("adwords"));
}
Can someone help please?
use my repository Milk JS in github.
<script src="https://raw.githubusercontent.com/GlowStone07/Milk-JS/main/src/milk.js" type="text/javascript" charset="utf-8"></script>
use the function get then the cookie name, returns cookie value.
FULL EXAMPLE:
//set new cookie
set("name", "John Doe");
//log the cookie's value
console log(get("name'));
//clear all cookies
clear();
//expected output: John Doe
If you want get getCookies function,you can try blow:
function getCookie(c_name) {
if (document.cookie.length > 0) {
c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1) {
c_start = c_start + c_name.length + 1;
c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) c_end = document.cookie.length;
return unescape(document.cookie.substring(c_start, c_end));
}
}
return "";
}

javascript cookies, create and delete

I'm working on a page that refreshes itself every 5 minutes
<meta http-equiv="refresh" content="1200;url=?meta_refresh=true" />
On the page is a JS script that should run the first two times the page reloads. When the page reload's for the third time, the script should not execute.
So far, I've created a cookie and given it an initial value of 0, for every refresh I increment it's value (rewrite the cookie) and if the value is smaller than 3 i execute the part of a script. The things is that if I close the tab and reopen the page in another tab, the cookie has the incremented value, and I want it to always start from 0.
Here's what i've done so far:
var value = 0;
$(document).ready(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 "";
}
function checkCookie() {
var cookieValue = getCookie('siteRefreshCookie');
if (cookieValue !== '') {
var newValue = parseInt(getCookie('siteRefreshCookie')) + 1;
if (newValue < 3) {
//script to be executed
document.cookie = "siteRefreshCookie="+ newValue +";";
}
} else {
document.cookie = "siteRefreshCookie="+ value +";";
}
}
checkCookie();
})
Could I suggest using a query string instead?
<meta http-equiv="refresh" content="1200;url=?meta_refresh=true&count=1" />
Then as an ASP programmer myself I would do something like:
<meta http-equiv="refresh" content="1200;url=?meta_refresh=true&count=<%=CInt(0 & Request.Querystring("count")) + 1%>" />
But you can probably achieve this using PHP, or even JS I imagine if you have no back-end language suitable.
The problem with using cookies is that they are tied to that website, rather than that window. Even if you reset the cookie with an unload function like Pete suggested, you'll then run into problems like if for example you have two tabs open with the same page.

How can I make a pop up stop appearing after a user clicks the link?

I've used JavaScript to set a cookie when the user clicks on the popup notice but after closing the browser completely, the cookie expires and the notice is shown again when navigating to the page.
I want the user to have the option to essentially say "Don't show this again".
1) Is there a better way to do this like saving the data to the db?
2) Can I set the cookie so it doesn't expire when the window is closed?
Here is the code to set the cookie. If cookie isn't set to "visited" it calls another function to showLightBox().
$j(document).ready(function() {
$j(function() {
checkCookie();
});
function checkCookie() {
var hasVisit = getCookie("hasVisited");
if(hasVisit != "visited") {
showLightBox();
}
}
function getCookie(c_name) {
var c_value = document.cookie;
var c_start = c_value.indexOf(" " + c_name + "=");
if (c_start == -1)
c_start = c_value.indexOf(c_name + "=");
if (c_start == -1)
c_value = null;
else
{
c_start = c_value.indexOf("=", c_start) + 1;
var c_end = c_value.indexOf(";", c_start);
if (c_end == -1)
c_end = c_value.length;
c_value = unescape(c_value.substring(c_start,c_end));
}
return c_value;
}
function setCookie(cookieName, value) {
document.cookie = cookieName + "=" + value;
}
You can set the date when the cookie will be expired like this.
document.cookie="username=suman; expires=Thu, 18 Dec 2020 11:00:00 GMT";
Now this cookie will be deleted on 18th dec 2020. By default the cookie will be deleted when your browser is closed.
Update:-
In your case the cookie will set with the date on which it will be expired.
function setCookie(cookieName,value){
document.cookie = cookieName+"="+value+"; expires=Thu, 18 Dec 2020 11:00:00 GMT";
}
You may put any date you want at date field.
Did you by any chance use a session cookie? they expire when you close the browser.
You can continue reading here :
Why cookies dont expire after closing browser?
You are probably not setting an expiration for the cookie, so it defaults to a session cookie that expires on browser close.
If you are already using jQuery I recommend using the wonderful jQuery Cookie plugin, which makes setting and retrieving cookies a total piece of cake. See the readme/documentation for details and enjoy only having to write a couple lines of code instead of 50.
Why don't you use localStorage in html5 for achieving this since it is persistent,
Like when a user clicks on the link for the first time set the flag
localStorage.setItem('clicked', "yes");
Then again check if this value is set,
if(localStorage.getItem('clicked')!=null){
//clicked
}
else
{
//not clicked
}
If this value is set then show "Don't show this again" else don't ...

GeoIP Redirect Loop - How to solve it?

I want to redirect my users to different languages/subfolders based on their IP address. To do this I use the JavaScript GeoIP API from MaxMind.
The problem: The english speaking people should stay at mydomain.com and not go to mydomain.com/en/. But when I redirect to mydomain.com the GeoIP script runs again which creates an infinite loop.
Here is my code (in index.html for mydomain.com):
<script language="JavaScript" src="http://j.maxmind.com/app/geoip.js"></script>
<script language="JavaScript">
var country = geoip_country_code();
if(country == "FR")
{
window.location = "http://mydomain.com/fr/"
}
else
{
window.location = "http://mydomain.com/";
}
</script>
In other posts I read about setting a cookie, but I wasn't able to do it in a way that solves the problem (and it would still create a loop when the user doesn't accept cookies, on mobile for example).
Another solution could be to redirect to mydomain.com/en/ and delete the /en/ folder in the URL via htaccess, but I wasn't able to get this done either.
An example of how I want it to work would be waze.com (it seems like they have the english version in the /en/ folder, but delete it from the URL).
So if anybody is able to help, I would be very grateful. Thanks a lot!
EDIT: I solved the problem myself. It's very simple: Just use the root directory for the english page and change function to "else {null;}" :-)
Your problem is not with geoip but with your code.
Try this:
var country = geoip_country_code();
var currentLocation = String(window.location);
//if geoip is equal FR and window.location is different "http://mydomain.com/fr/"
if(country === "FR" && currentLocation.indexOf("http://mydomain.com/fr/")!==0)
{
window.location = "http://mydomain.com/fr/"
}
//if geoip is different FR and window.location is equal "http://mydomain.com/fr/"
else if(currentLocation.indexOf("http://mydomain.com/fr/")===0)
{
window.location = "http://mydomain.com/";
}
To detect using multiple languages ​​simply edit the following variables:
var defaultsLang are the languages ​​that are supported by the main root (site.com/)
var languages languages supported by sub-pages (site.com/fr/, site.com/es/, etc.)
See code (not tested):
(function(){
var defaultsLang = ["en-us","en"];
var languages = {
"fr": true, //enable french pages
"pt": false, //tmp disable portuguese pages
"es": true //enable spanish pages
};
var country = geoip_country_code().toLowerCase(),
currentLocation = String(window.location),
detectCurrent = function(){
var a = currentLocation.replace(/^(http|https)[:]\/\//, "");
var b = a.split("\/");
b = b[1].toLowerCase();
a = null;
return b.length<5 && (/^[a-z\-]+$/).test(b) ? b : false;
};
var currentLang = detectCurrent();
defaultsLang = "|"+defaultsLang.join("|")+"|";
if(currentLang!==country && typeof languages[country] !=="undefined" && languages[country]!==false){
window.location = "http://mydomain.com/" + country + "/";
} else if(
defaultsLang.indexOf("|" + currentLang + "|")===-1 && //current page is not the same as default languague(s)
defaultsLang.indexOf("|" + country + "|")!==-1 && //geoip is in the list of default language(s)
currentLang!==false
){
window.location = "http://mydomain.com/";
}
})();

Click to make body text larger | JavaScript

Please note this is just an example:
<img src="img/normal-font.png" onclick="javascript:document.body.style.fontSize = '13px';" />
<img src="img/medium-font.png" onclick="javascript:document.body.style.fontSize = '14px';" />
<img src="img/large-font.png"onclick="javascript:document.body.style.fontSize = '15px';" />
The body text does indeed enlarge if I choose one of them, but what I like to include is remembering what option you've chosen by reading cookies.
In fact, I have no experience in creating cookies in JS, only in PHP. Could someone come up with an example of how to make cookies the simpliest way remembering my option, but whenever someone clicks another one, it should get rid of the cookie that was last set, e.g. Cookie value has 15px, then should update it or remove it with a new cookie with a new value of 13px and so on.
Thanks :)
you can set and get the cookie values from javascript in the same way you do in php.
you can use the following two methods for your help.
function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
}
function getCookie(c_name)
{
if (document.cookie.length>0)
{
c_start=document.cookie.indexOf(c_name + "=");
if (c_start!=-1)
{
c_start=c_start + c_name.length+1;
c_end=document.cookie.indexOf(";",c_start);
if (c_end==-1) c_end=document.cookie.length;
return unescape(document.cookie.substring(c_start,c_end));
}
}
return "";
}
have a look into this page for more details.
This might Help:
QuirksMode Javascript cookies reference.

Categories