Trying to create cookies in JavaScript - javascript

I am trying to save cookies in JavaScript and then display them on the page again but for some reason my setCookies function and displayCookies function is not working properly.. I want it to also expire after 1 week. It is coming from a form and when I put it in Web Developer in FireFox it says Reference Error setCookies and displayCookies is not defined. My jsfiddle is : http://jsfiddle.net/FmXJW/
function setCookies()
{
// this function will set cookies for each field in the reservation form, and set them to expire after one day
var Name = document.forms[0].txtName.value;
var Address = document.forms[0].txtAddress.value;
var City = document.forms[0].txtCity.value;
var State = document.forms[0].txtState.value;
var Zip = document.forms[0].txtZip.value;
var Email = document.forms[0].txtEmail.value;
var CarType = document.forms[0].txtCarType.value;
var PickupDate = document.forms[0].txtPickupDate.value;
var ReturnDate = document.forms[0].txtReturnDate.value;
var myDate = newDate();
myDate.setDate(myDate.getDate() + 7);
document.cookie = "name=" + encodeURIComponent(Name) + "; expires=" + myDate.toUTCString();
document.cookie = "address=" + encodeURIComponent(Address) + "; expires=" + myDate.toUTCString();
document.cookie = "city=" + encodeURIComponent(City) + "; expires=" + myDate.toUTCString();
document.cookie = "state=" + encodeURIComponent(State) + "; expires=" + myDate.toUTCString();
document.cookie = "zip=" + encodeURIComponent(Zip) + "; expires=" + myDate.toUTCString();
document.cookie = "email=" + encodeURIComponent(Email) + "; expires=" + myDate.toUTCString();
document.cookie = "carType=" + encodeURIComponent(CarType) + "; expires=" + myDate.toUTCString();
document.cookie = "pickupDate=" + encodeURIComponent(PickupDate) + "; expires=" + myDate.toUTCString();
document.cookie = "returnDate=" + encodeURIComponent(ReturnDate) + "; expires=" + myDate.toUTCString();
window.alert ("Your reservation has been saved.");
} // end function setCookies()
function displayCookies()
{
// this function will read the saved cookies, and repopulate the form with the cookie values
var cookieString = decodeURIComponent(document.cookie);
var cookieArray = cookieString.split("; ");
if (document.cookie == 0)
{
alert("You have not made a reservation");
}
else
{
// retrieve each cookie, and display the cookie value in the appropriate form field
document.forms[0].txtName.value = cookieArray[0].lastIndexOf("=") + 1);
document.forms[0].txtAddress.value = cookieArray[1].lastIndexOf("=") + 1);
document.forms[0].txtCity.value = cookieArray[2].lastIndexOf("=") + 1);
document.forms[0].txtState.value = cookieArray[3].lastIndexOf("=") + 1);
document.forms[0].txtZip.value = cookieArray[4].lastIndexOf("=") + 1);
document.forms[0].txtEmail.value = cookieArray[5].lastIndexOf("=") + 1);
document.forms[0].txtCarType.value = cookieArray[6].lastIndexOf("=") + 1);
document.forms[0].txtPickupDate.value = cookieArray[7].lastIndexOf("=") + 1);
document.forms[0].txtReturnDate.value = cookieArray[8].lastIndexOf("=") + 1);
}
} // end function displayCookies()

You have a couple of problems on your code:
You are not retrieving the value from the different fields stored on the cookie correctly, you need to use slice to get the right part.
I also guess the line var myDate = newDate(); should be var myDate = new Date();.
I have changed your fiddle (find it here) and loaded the code in <head> and now it seems to save and display the cookies correctly.

Related

How can I set a button to create a cookie with an increased numerical name and unique value (based on a variable) each time it is clicked?

I am trying to create a button that creates a new cookie with an increased numeric value as it's name and a different value (which comes from a variable), each time it is clicked. But, I can't get it to work.
This is what I have:
var date = new Date()
date.setTime(date.getTime() + 7*24*60*60*1000);
var num=1;
function addCookie() {
var expString = "; expires=" + date.toGMTString();
var cookievalue=escape(document.button.addpart.value) + ";";
document.cookie=num + "=" + cookievalue + expString + "; path=/my-quote/";
num++;
}
Then the html is:
<button name="addpart"; value="<?php $pn ?>"; onclick='addCookie()'>ADD</button>
I started with the following code (which worked, but just created a new cookie with the name 1 and value 1, then 2 and 2, 3 and 3 etc. I adapted it, so I think that's where I have gone wrong or missed something:
var num=1;
function addCookie() {
document.cookie=num+"="+num;
num++;
}
Updated code
var date = new Date() date.setTime(date.getTime() + 7 * 24 * 60 * 60 * 1000);
var num = 1;
function addCookie() {
var expString = "; expires=" + date.toGMTString();
var cookievalue = escape(document.querySelector("[name=addpart]").value) + ";";
document.cookie = num + "=" + cookievalue + expString + "; path=/my-quote/";
}

Cookies are not being expired/removed in all browsers

I have set few cookies for my ecommerce website to keep track of users ordered items, if users choose to delete those items the cookies should also be deleted, however for some odd reason safari is not deleting those cookies. any other browser the cookies are being deleted fine.
Here is the link for the website if anyone wants to have a look: (link not available anymore) click on first item "blankets and towels" then choose any items from the 3 options, add it to card then go to basket, you should see on top left corner "numbers of cookies = 5" if u ordered more items it will increase, once all items is deleted from the cart it should say "numbers of cookies = 3" however in safari it still says 5.
Javascript
if(confirm("Are you sure you want to delete this item"))
{
var i = 1;
while(true){
var value = "; " + document.cookie;
var parts = value.split("; " + "order"+i + "=");
if(parts.length === 2){
var results = parts.pop().split(";").shift();
var temp = results.split(" ");
if(temp[0] === id)
{
var d = new Date();
d.setTime(d.getTime() + 1000*60*60*24*60);
var exp = "expires=" + d.toUTCString();
var name = "order"+i;
temp[2] = temp[2] - 1; **REmove one item from order**
var val = temp[0] + " " + temp[1] + " " + temp[2];
if(temp[2] === 0){ **if cookie has 0 items then delete cookie**
document.cookie = name + "=" + '' + ";" + '=;expires=Thu, 01 Jan 1970 00:00:01 UTC;'+ ";path=/";
setNewTotal();
}else{
document.cookie = name + "=" + val + ";" + exp + ";path=/";
setNewTotal();
}
window.location.reload(true);
break;
}
}
i++;
}
window.location.reload(false);
}else{
}
}
function setNewTotal(){
var value = "; " + document.cookie;
var parts = value.split("; " + "totalOrders=");
if(parts.length === 2) {
var results = parts.pop().split(";").shift();
}
results = results - 1;
var d = new Date();
if(results === 0){
document.cookie = "totalOrders=" + '' + ";" + '=;expires=Thu, 01 Jan 1970 00:00:01 UTC;' + ";path=/";
}else{
d.setTime(d.getTime() + 1000*60*60*24*60);
var exp = "expires=" + d.toUTCString();
document.cookie = "totalOrders=" + results + ";" + exp + ";path=/";
}
}
I figured it out when deleting the cookies I specified the time wrong, seems all other browsers ignored it except safari.
old code:
document.cookie = "totalOrders=" + '' + ";" + '=;expires=Thu, 01 Jan 1970 00:00:01 UTC;' + ";path=/";
New code
document.cookie = "totalOrders=" + '' + ";" + 'expires=Thu, 01 Jan 1970 00:00:01 UTC;' + ";path=/";
Notice that '=;expires=Thu,' was replaced with 'expires=Thu,' this is because I had already set = "totalOrders=" + '' + ";" therefore there was no need for =;
Thank you for the help very appreciate :)

Multiple values on one cookie

The code I wrote should store multiple user values on one cookie, but for some reason it's not working. Can anyone care to explain my mistake?
var delimiter = "#";
function createCookie(name, value, days, path, domain, secure) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = date.toGMTString();
} else var expires = "";
cookieString = name + "=" + escape(value);
if (expires)
cookieString += "; expires=" + expires;
if (path)
cookieString += "; path=" + escape(path);
if (domain)
cookieString += "; domain=" + escape(domain);
if (secure)
cookieString += "; secure";
document.cookie = cookieString;
}
function getCookie(name) {
var nameEquals = name + "=";
var whole_cookie = document.cookie.split(nameEquals)[1].split(";")[0];
var crumbs = whole_cookie.split(delimiter);
}
function deleteCookie(name) {
createCookie(name, "", -1);
}
function myCookie() {
var name = document.getElementById('name').value;
var age = document.getElementById('age').value;
var userdata = name + delimiter + age;
createCookie("user", userdata);
var myUser = getCookie('user');
var myUserArray = myUser.split(delimiter);
var cookieName = myUserArray[0];
var cookieAge = myUserArray[1];
alert('The cookie created has the following user information stored on it: \nName: ' + cookieName '\nAge: ' + cookieAge);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
Please enter your name
<input type=text id='name' />
<br>
<br>Please enter your age
<input type=text id='name' />
<input type=button value='Go!' onClick='myCookie()' />
There are a couple of mistakes in your code:
In getCookie, you forgot to return the value of your cookie !
function getCookie(name) {
var nameEquals = name + "=";
var whole_cookie=document.cookie.split(nameEquals)[1].split(";")[0];
return whole_cookie;
}
You have two inputs with id name, I think you want to rename one of them to age.
Make sure your document is fully loaded before you try to execute your Javascript! Either do that by wrapping your code around document.body.onload = function(){ [your code here] }, or by moving your <script> tag at the end of your document.
You are missing a + between cookieName and '\nAge' in your alert.
var delimiter = "#";
function createCookie(name, value, days, path, domain, secure) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = date.toGMTString();
} else var expires = "";
cookieString = name + "=" + escape(value);
if (expires)
cookieString += "; expires=" + expires;
if (path)
cookieString += "; path=" + escape(path);
if (domain)
cookieString += "; domain=" + escape(domain);
if (secure)
cookieString += "; secure";
document.cookie = cookieString;
}
function getCookie(name) {
var nameEquals = name + "=";
var whole_cookie = document.cookie.split(nameEquals)[1].split(";")[0];
return whole_cookie;
}
function deleteCookie(name) {
createCookie(name, "", -1);
}
function myCookie() {
var name = document.getElementById('name').value;
var age = document.getElementById('age').value;
var userdata = name + delimiter + age;
createCookie("user", userdata);
var myUser = getCookie('user');
var myUserArray = myUser.split(delimiter);
var cookieName = myUserArray[0];
var cookieAge = myUserArray[1];
alert('The cookie created has the following user information stored on it: \nName: ' + cookieName + '\nAge: ' + cookieAge);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
Please enter your name
<input type=text id='age' />
<br>
<br>Please enter your age
<input type=text id='name' />
<input type=button value='Go!' onClick='myCookie()' />

Set Expiration on end of the day

I'm trying to set a cookie that will expire at the end of the day. I've create this function :
function mnc(cname,cvalue)
{
var now = new Date();
var expire = new Date();
expire.setFullYear(now.getFullYear());
expire.setMonth(now.getMonth());
expire.setDate(now.getDate()+1);
expire.setHours(0);
expire.setMinutes(0);
//alert(expire.toGMTString() + " " + expire.toString());
var expires = "expires="+expire.toString();
alert(expires + "=> now =" + now);
document.cookie = cname + "=" + cvalue + "; " + expires +"; path=/";
}
On Fiddle : http://jsfiddle.net/MYs6b/
So, the alert box show me the good expiration date.
But, if I change the date on my computer by adding 1 or 100 days, i still have the same value in the cookie.
Why? I'm searching since 3 hours and i don't understand...
EDIT :
I've had an alert on "document.cookie" is empty
http://jsfiddle.net/MYs6b/2/
EDIT 2 :
I've add a better example of my problem. It's working on IE and FF but not on chrome :
http://jsfiddle.net/5h87M/1/
Try This: http://jsfiddle.net/MYs6b/1/
function mnc(cname,cvalue)
{
var now = new Date();
var expire = new Date();
expire.setFullYear(now.getFullYear());
expire.setMonth(now.getMonth());
expire.setDate(now.getDate()+1);
expire.setHours(0);
expire.setMinutes(0);
expire.setSeconds(0);
var expires = "expires="+expire.toString();
alert(expires + "=> now =" + now);
document.cookie = cname + "=" + cvalue + "; " + expires +"; path=/";
}
mnc("test", "123456");
Last update of chrome correcting this issue.
function createCookie(name,value,path) {
var expires = "";
var date = new Date();
var midnight = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 23, 59, 59);
expires = "; expires=" + midnight.toGMTString();
if (!path) {
path = "/";
}
document.cookie = name + "=" + value + expires + "; path=" + path;
}

Cuts off form data when setting url as value

This script creates a cookie depending on form data, (ex: ?docname=My Document)
<script type="text/javascript">
{
var docname = getValue("docname"); // these go off another script to get form data
var save = getValue("save");
var url = window.location.href;
}
function setCookie(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=/";
}
function saveDoc() {
if (docname != '') {
setCookie(docname,url,730);
}
else {
// Nothing else to do
}
}
// Helps to find errors if they exist
window.onerror = function(errorMessage, url, line) {
var errorText = 'message: ' + errorMessage + '\nurl: ' + url + '\nline: ' + line + ' please contact us, and report this error.';
alert(errorText);
}
</script>
It creates the cookie and sets the name of it as the docname variable, but when it sets the url as the value, it cuts off the form data.
I've researched and changed the code but couldn't find an answer, can anyone help?
Solution
<script type="text/javascript">
{
var docname = getValue("docname"); // these go off another script to get form data
var save = getValue("save");
var url = window.location.href;
var recode = encodeURIComponent(url);
}
function setCookie(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=/";
}
function saveDoc() {
if (docname != '') {
setCookie(docname,recode,730);
}
else {
// Nothing else to do
}
}
// Helps to find errors if they exist
window.onerror = function(errorMessage, url, line) {
var errorText = 'message: ' + errorMessage + '\nurl: ' + url + '\nline: ' + line + ' please contact us, and report this error.';
alert(errorText);
}
</script>
changed the variable used to set the value to recode and set recode equal to encodeURIComponent(url); so it decodes the url, decoding it and making it possible to have form data in a value or name of a cookie, etc. Thanks to #epascarello
encodeURIComponent() is your friend here
document.cookie = name + "=" + encodeURIComponent(value) + expires + "; path=/";
and when you get it, you need to decode it with decodeURIComponent().

Categories