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 "";
}
Related
I recently was given a solution to checking if a pop up has been shown and then only showing it once using cookies. But after implementing cookies the pop up no longer shows. I have googled the issue, and tried to find a solution but my lack of knowledge on the subject has made it difficult for me to understand the issue and fix it.
This is the code i am using, i have implemented the use of cookies and i believe that they should work but the pop up however is not working
function setCookie(cname,cvalue) {
document.cookie = cname + "=" + cvalue;
}
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 "";
}
function checkCookie() {
var user=getCookie("ageverification");
if (user != "") {
return null;
} else {
var overlay = $('<div id="overlay"></div>');
overlay.show();
overlay.appendTo(document.body);
$('.popup').show();
$('.close').click(function() {
$('.popup').hide();
overlay.appendTo(document.body).remove();
return false;
user = true;
setCookie("ageverification", user);
});
}
}
function goBack() {
window.history.go(-2);
}
<div class='popup'>
<div class='cnt223'>
<h1>Important Notice</h1>
<p>
You must be over 18 to Purchase products on this website!
<br/>
<br/>
I Am Over 18
I Am Not
</p>
</div>
</div>
I applied some changes to your code and now it should work.
As a summary, I applied these changes:
removed dead code from checkCookie;
simplified the code for getCookie;
eliminated the overlay div (which did nothing: it was just created empty, attached to the DOM and then removed from it);
changed "popup" from a class to an id;
made the selector strings more specific.
To improve the getCookie function, I eliminated an unnecessary loop and a few substrings. You can get to the same result more cleanly using the trim method (which eliminates preceding and trailing whitespace from a string) and splitting the cookie by "=".
To improve checkCookie, I eliminated some dead code (which couldn't run because it was after a return statement), some redundant one (which declared variables for values needed only once) and the apparently useless div tag. Also, I changed the selector strings to explicitly reference the "a" node inside the popup and I added a call to preventDefault(). This last part (changing the selector strings and calling preventDefault) was the one solving the issue.
function setCookie(cname,cvalue) {
document.cookie = cname + "=" + cvalue;
}
function getCookie(cname) {
var ca = decodeURIComponent(document.cookie).split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i].trim().split('=');
if (cname == c[0] && c.length > 1) {
return c[1];
}
}
return "";
}
function checkCookie() {
if (getCookie("ageverification") == ""){
$('#popup').show();
$('#popup a.close').click(function (event) {
event.preventDefault();
$('#popup').hide();
setCookie("ageverification", 'true');
});
$('#popup a.goBack').click(function ( event ) {
event.preventDefault();
goBack();
});
} else {
return null;
}
}
function goBack() {
window.history.go(-2);
}
<div id='popup'>
<div class='cnt223'>
<h1>Important Notice</h1>
<p>
You must be over 18 to Purchase products on this website!
<br/>
<br/>
I Am Over 18
I Am Not
</p>
</div>
</div>
After click on button in first.html, i have been called a function and updated labels in second.html, but i able to see a second.html not able to see the updated value in labels in second.html.Please help me how to achieve.
function updateLabels(){
$('#entryNumber').text("123");
$('#responsedate').text("23-9-2015");
window.location = 'second.html';
}
ex:second.html
<body>
<label>Entry Number:</label>
<label id="entryNumber" for="entryNumber"></label><br><br>
<label>Respond Date:</label>
<label id="responsedate" for="responsedate"></label><br><br>
<label>Response Text:</label>
</body>
You can achieve your goal in client side via.. 3 options
1. By Local Storage
On first page set your second page label value in local storage.
// In 1st page
function updateLabels(){
localStorage.setItem('Second_Page_LabelVal', "apple");
window.location = 'second.html';
}
On second Page get this value from local storage and set it to your labels value
// In 2ndPage
$( document ).ready(function() {
// Retrieve the object from storage
var retrievedVal = localStorage.getItem('Second_Page_LabelVal');
$("2ndpagelabelId").text(retrievedVal);
});
2. By cookie
On first page set your second page label value in COOKIES.
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
// In 1st page
function updateLabels(){
createCookie(('Second_Page_LabelVal', "apple",1);
window.location = 'second.html';
}
On second Page get this value FROM COOKIE and set it to your labels value
// In 2ndPage
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;
}
$( document ).ready(function() {
// Retrieve the object from cookie
var retrievedVal = readCookie('Second_Page_LabelVal');
$("2ndpagelabelId").text(retrievedVal);
});
3. By querystring Url
Redirect page with second page value in query string
// In 1st page
function updateLabels(){
window.location = 'second.html?SecondpageValue=value1';
}
Get the value from url and set it to label.
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" :
decodeURIComponent(results[1].replace(/\+/g, " "));
}
$( document ).ready(function() {
// Retrieve the object from url
var retrievedVal = getParameterByName('SecondpageValue');
$("2ndpagelabelId").text(retrievedVal);
});
Html page DOES NOT save your status, and we needs a server-side program to handle usually.
In your case, maybe a modal dialog is useful.
Try using $.get() , substitute .replaceWith() for window.location at same document
function updateLabels(html){
$(html).find("#entryNumber").text("123");
$(html).find("#responsedate").text("23-9-2015");
$("body").replaceWith(html);
}
$.get("second.html", updateLabels);
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.
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 ...
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.