Why isn't my cookie being set? - javascript

I am learning, please be kind if it is an obvious mistake.
/*set cookie*/
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 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;
}
function eraseCookie(name) {
setCookie(name,"",-1);
}
$(window).load(function() {
//check for the cookie
var language = readCookie('language');
//if null show red
if (language!=null)
{
$('.blue').hide();
alert('No cookie set');
}
//if null show red
else if (language!=red)
{
$('.blue').hide();
alert('The cookie is red');
}
//if blue show blue
else {
$('.red').hide();
alert('The cookie is set to blue');
}
$('#blue').click(function() {
$('.red').hide();
$('.blue').show();
setCookie('language','blue', 30);
alert('The cookie is set to blue');
});
$('#red').click(function() {
$('.red').show();
$('.blue').hide();
setCookie('language','red', 30);
alert('The cookie is set to red');
});
});
Thank-you.

Learning to use Firebug is the best advice. Another helpful tool is a colorizing editor. Even SO provides a little help of this kind. Note the line:
else if (language!=red)
"red" wasn't colored as a string, so it stood out by not standing out. Is there a variable named "red" defined somewhere in the original code? If not, this compares language to undefined.
Also, consider the lines that follow this statement:
else if (language!='red') {
$('.blue').hide();
alert('The cookie is red');
You just tested that the cookie value was not red, but you alert that it is. You make a similar mistake on the first test:
if (language!=null) {
$('.blue').hide();
alert('No cookie set');
language is not null, but the message you display suggests it is.
This isn't related to your question, but there are some simplifications you can make. For one, jQuery defines a trim method on String to remove leading and trailing whitespace. Make use if this in readCookie rather than the while (c.charAt(0)==' ') loop.
Another improvement is that the current technique of choosing an element to show by using a sequence of if blocks doesn't scale well. Your homework is to use string operations and whatnot to better handle an arbitrary number of elements, then add ".green", ".yellow", ".magenta" and ".cyan" elements. You might need to change the default behavior from showing all .color elements to hiding them. Using objects as associative arrays may also be helpful.

If you're learning the best answer to your question here would probably be some debugging tips. What are you using for debugging?
Have you tried Firebug in Firefox. http://getfirebug.com/ This will let you step through your code one line at a time and inspect exactly what it is doing, what values are really being passed to functions, and exactly what string you are assigning to document.cookie.

Related

What is the purpose of while and for loops, if statement in this code?

I'm trying to understand the concept of Cookies in JavaScript. For that, I'm trying to understand the working of this code from http://www.w3schools.com/js/tryit.asp?filename=tryjs_cookie_username:
<script>
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}
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 user=getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:","");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
}
}
</script>
I've understood most of the things in this code, but still I have some doubts/queries (in getCookie function):
Doubt 1. Purpose of for loop
Doubt 2. Purpose of if
Doubt 3. Purpose of while loop
Doubt 4. Purpose of return "";
I'm asking about these because the script is running fine even without using these conditions. (I know the working of each inbuilt function in getCookie function. I just don't understand the use of above loops and conditions).
Here's what I want to say:
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
var c = ca[0];
return c.substring(name.length, c.length);
}
Even after I've changed the expiry date to a past date in setCookie function (exdays*2000), it is still displaying "Welcome to XYZ" message. That means Cookie is not deleted. But when I run the same code in a different browser, it is deleted. Why is so?
Doubt 1. Purpose of for loop
All cookies are saved as a semicolon separated key-value (actually it is semicolon and space ;). key and values are separated by equal-to (=) symbol. By iterating, you are checking all the keys and returning only the value of key which is matching the argument passed to the method
Doubt 2. Purpose of if
To check if the current key from the iteration contains the cookie name that is passed to the method.
Doubt 3. Purpose of while loop
To remove all spaces one by one. Actually this one can easily be improved by using trim() method.
//while (c.charAt(0)==' ') c = c.substring(1);
c = c.trim();
Doubt 4. Purpose of return "";
if there is no value found, then return an empty string rather than user having to check for the null or undefined.
Even after I've changed the expiry date to a past date in setCookie
function (exdays*2000), it is still displaying "Welcome to XYZ"
message. That means Cookie is not deleted. But when I run the same
code in a different browser, it is deleted. Why is so?
It is possible (assuming this, since you have not shared any fiddle) that your setCookie method is not executed when you opened that page second time on the same browser.
Doubt 1. Purpose of for loop
Cookies are stored as a single line string like this:
"Cookie_1=Cookie_value1; Cookie_2=Cookie_value2; Cookie_3=Cookie_value3; Cookie_4=Cookie_value4;"
Then this is split into arrays with
var ca = document.cookie.split(';');
So the value of ca is now ["Cookie_1=Cookie_value1"," Cookie_2=Cookie_value2"," Cookie_3=Cookie_value3"," Cookie_4=Cookie_value4",""]
which can be considered a cookie "entity" for each member of the array
Doubt 3. Purpose of while loop
If you look at the values in the ca array, you will see that Cookie 2 has a value of " Cookie_2=Cookie_value2". There are leading spaces that we need to trim out so there goes the purpose of this while loop
while (c.charAt(0)==' ') c = c.substring(1);
Doubt 2. Purpose of if
After the leading spaces are trimmed then you can check if the cookie name matches the one you are looking for.
For example, "Cookie_3=Cookie_value3".indexOf("Cookie_3=") is equal to 0
Doubt 4. Purpose of return "";
This is just the default value to return if the cookie name specified is not found, something like a case default in switch case.

script for on load alert box based on url

I am creating a submittal form, sending the form to a php form, and after the form completes having it redirect to the initial page with an additional "?s=1" in the url.
Basically what I am trying to do is create an alert box pop up on loading the page with the "?s=1" in the url.
It is a very brute force method to use I know, but i can't seem to get the small script to work correctly. I know for certain everything works and loads to the point and reloads the initial page with ?s=1 in it.
Here is the code i'm using to try and prompt the alert box
enter code here <script type="text/javascript">
var Path = window.location.href;
if (Path == "mywebsite.html?s=1")
{
alert("Your Form Has Been Submitted.")
}
else()
{
}
</script>
Does anybody know why the box will not appear? Or possibly an alternate method for what I am attempting to do? Thanks.
window.location.href contains the complete URL, including the domain, and the full path, so a basic equality comparison won't work unless you're exaclty matching it, and even still this could cause problems (e.g. www. versus a naked domain, https:// versus http://, etc.). A possible solution is to use RegEx.
var pathRegex = /mywebsite\.html\?s\=1/;
if (pathRegex.test(window.location.href)) {
alert("Your Form Has Been Submitted.")
}
As a note, you can have an if statement without an accompanying else, and else statements don't take any arguments in parentheses like if, unless you're talking about else if.
Here is some code I wrote up for one of my projects that lets you pull a parameter and value out of the url.
function GetURLParameter(urlParameter){
var url = window.location.search.substring(1);
var urlVariables = url.split('&');
for (var i = 0; i < urlVariables.length; i++){
var parameter = urlVariables[i].split('=');
if (parameter[0] == urlParameter){
return parameter[1];
}
}
}
It's easy to use:
For mywebsite.com?s=1
It would just be
var k = GetURLParameter('s');
if (k == 1){
alert("Your Form Has Been Submitted.")
}
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, " "));
}
And then check like...
if (getParameterByName("s")=="1")
{
alert("Your Form Has Been Submitted.")
}
else
{
}

cookies dont work on Chrome

I am using a simple javascript code like this to play around with cookies
var theCookie = "login = ScottPilgrimVStheWorld";
document.cookie=theCookie;
alert(document.cookie);
I have just a simple html page with a body, a header and this javascript code.
Problem is , this is working in IE and FF but not in GC 33.0.1750.154 m. I get an empty alert box. I took a glance at the GC settings and found nothing on blocking/unblocking Cookies. What is happening? Any tips?
Thanks in advance.
EDIT
Here is another function for reading cookies
function getCookie(searchName)
{
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++)
{
var cookieCrumbs = cookies[i].split("=");
var cookieName = cookieCrumbs[0];
var cookieValue = cookieCrumbs[1];
if (cookieName == searchName)
{
return cookieValue;
}
}
return false;
}
"The JavaScript Anthology 101 Essential Tips, Tricks & Hacks" by James Edwards and Cameron Adams, Copyright © 2006 SitePoint Pty. Ltd., pp145-146
Try modifying variable theCookie:
var theCookie = "login=ScottPilgrimVStheWorld;";
We must do this because as stated in W3Schools, the template for a cookie is
[cookie-name]=[cookie-name-val]; [Next is optional] expires=[expiry_date].
Also, I don't think you can just get the cookie directly like that. You have to create a function:
function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
So you change your alert to something like this:
alert(getCookie("login"));
Hope that helped.
No spaces are allowed in the assignment string added to the cookie jar. Try
var theCookie = "login=ScottPilgrimVStheWorld";
Tested on chrome 33 ( 33.0.1750.154 ).
edit:
chris97ong is right in his claim that you need additional logic to extract a single cookie from the cookie jar document.cookie. if you need that, use his code or match against a regex:
var mycookie = document.cookie.replace(/(^|;)login=([^;]+)(;|$)/, "$2");

Removing Cookie value from browser

I know that this has been asked many times, and ive tried using the accepted answers. But sadly none of that seems to work for me in my browser(Mozilla v18.0.2).
I am using backbone for my website and im using cookies to handle user login sessions.
The following are the unsuccessful ones :
Code 1
var cookie_date = new Date ( ); // now
cookie_date.setTime ( cookie_date.getTime() - 1 ); // one second before now.
// empty cookie's value and set the expiry date to a time in the past.
document.cookie = "uid=;expires=" + cookie_date.toGMTString();
document.cookie = "userName=;expires=" + cookie_date.toGMTString();
Code 2
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){
uid = c.substring(nameEQ.length,c.length);
return uid;
}
};
Any working solution for removing browser cookies??
Thanks
Roy
Simple answer
You can't.
Long answer
You can overwrite the cookie and give it an expiration time in the past.
Browsers will discard it at some point after its expiration. Until then you need to check yourself, if it has been “deleted”, e. g. with a special value or by comparing the expiration date with the current time.

Javascript Cookie Value defined

I am having trouble grasping what the 'value' field of a cookie needs to be. Does the 'value' field need to reference a variable found somewhere with the following javascript code, or is it something completely random?
The reason I ask, is b/c I am trying to put cookies on a project I am working on, but obviously I can't get them to work... here is what I have so far, but my main question is an elaborate definition of the value (physics) field and possibly an example that references some Jscript.
function createCookie(child,physics,d82){
if (d82) {
var date = new Date();
date.setTime(date.getTime()+(82*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = child+"="+physics+expires+"; path=/";
}
function readCookie(child) {
var nameEQ = child + "=";
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;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
The cookie is sent between the server and the browser as text, so the cookie value has to be a string, or something that can be converted to a string. When you read the cookie you will get the string back.
If you for example store the value 42 in a cookie, it will be converted to the string representation of the number. When you read the cookie, you will get the string "42" back, so if you want it as a numeric value, you have to parse the string.
The cookie value can be anything you want. You could for example store a user's country selection in a cookie, so that you only have to ask the user once:
createCookie('country', country, true);
Think of it as a key value pair.
You can give your cookie a name and a value. remember you can have multiple cookies, so the name identifies which on you are referring to, and the value...well I guess it stores the value :)
So for instance I have a cookie called "customerId", the value portion could be "bob"
Refer to http://www.w3schools.com/JS/js_cookies.asp

Categories

Resources