I was writing this code that is based on a tutorial and on the tutorial the code works, but when I try to do it by myself it doesn't. Can you help me ?
The code : (Tutorial Link).
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var user_name;
var expires = new Date();
if ((document.cookie == "") == false)
{
var length = document.cookie.length - 1;
var message = document.cookie.substr(5, length);
document.write("<h2><center>Welcome back, " + message + "</center></h2>");
}
function check()
{
user_name = document.getElementById("name").value;
expires.setFullYear(expires.getFullYear() + 1);
document.cookie = escape("name") + escape(user_name) + "; expires = " + expires.toGMTString();
alert(document.cookie);
}
</script>
<meta charset="utf-8">
<title></title>
</head>
<body>
Name: <input type="text" id="name" />
<input type="button" value="Enter" onClick="check()" />
</body>
</html>
Because you've mentioned I was creating this code that is tutorial based and on the tutorial, so if it's just for a test myself thing then you may consider to use this one (Demo Here), just enter a name and value for the cookie in the cookie name and cookie value fields respectively, when you want to Add a new cookie and to Delete a cookie just enter the name of the cookie in the cookie name field and same for View, you can add a Delete All buttons only by splitting cookies using & and making a loop and calling the eraseCookie() function, try it yourself.
Also there are already better ones are available on the web to use in the real case, but this one is not bad at all.
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=/";
return true;
}
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) {
if(!name) {
alert('\nPlease enter the name of cookie in cookie the name field.');
return false;
}
if(readCookie(name)){
if(createCookie(name,"",-1)) {
alert('Cookie "' + name + '" has been deleted!');
}
}
else alert('Cookie "' + name + '" doesn\'t exist!');
}
function addCookie()
{
cookie_name = document.getElementById("cName").value.replace(/^\s+|\s+$/g,'');
cookie_value = document.getElementById("cValue").value.replace(/^\s+|\s+$/g,'');
if(cookie_name.length && cookie_value.length){
createCookie(cookie_name, cookie_value, 7);
alert("New cookie has been added, \ncookie name : " + cookie_name + "\ncookie value : " + cookie_value);
}
else{
alert("Please enter a name and value for the cookie.");
}
}
function showCookie(name)
{
if(!name) {
alert('\nPlease enter the name of cookie in the cookie name field.');
return false;
}
var val = readCookie(name);
if(val){
alert(readCookie(name));
}
else alert('Cookie "' + name + '" doesn\'t exist!');
}
// Onload to check and greet
if(name = readCookie('name')) alert('Welcome back, ' + name);
Example Here.
Related
I am coding a game and I need to save some variables with cookies. I added a line that should execute a Javascript function that will check if the user has already been on the website and made an account or not, and if they have not it will ask for a username. However, when I added the line that should run the function, the function after it failed, and so did it.
This is a portion of my code:
<script>
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 + ";path=/";
}
function checkCookie() {
var username=getCookie("username");
if (username!="") {
alert("Welcome again " + username);
} else {
username = prompt("Please enter your username:", "");
if (username != "" && username != null) {
setCookie("username", username, 365);
}
}
}
</script>
<button id="open_market">Market</button>
<script>
checkCookie();
open_market.onclick = function() {
window.open("https://thenumnut.github.io/Wars-of-Shares/Market");
}
</script>
The line that I added to run the function was "checkCookie();". After I added that line the button with id "open_market" would not respond when clicked. This makes me think that the code failed/crashed on the line before it when I said "checkCookie();".
If anybody can find the problem with this code I will greatly appreciate it. You can see in the code the github link to my code on github if you would like to see my full code.
I added your getCookie() function, and apart from that, just added a bit of HTML around the tags, and here's the code:
<!DOCTYPE html> <html> <head> <script> 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 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 + ";path=/"; } function checkCookie() {
var username=getCookie("username");
if (username!="") {
alert("Welcome again " + username);
} else {
username = prompt("Please enter your username:", "");
if (username != "" && username != null) {
setCookie("username", username, 365);
}
} } </script> </head> <body> <button id="open_market">Market</button> <script> checkCookie(); open_market.onclick = function() { window.open("https://thenumnut.github.io/Wars-of-Shares/Market"); } </script> </body> </html>
It seems to be working fine
In JavaScript this is often a sign, that there is a bug in checkCookie();. I don't see one at first glance, but your browser should show you the bug in his console.
You can open the console in most browsers (e.g. Firefox, IE) by rightclicking somewhere on your page and then choose "Inspect Element". Now change to the tab Console.
If you don't understand the error message, just post it here
Open your browser's developer tools. Read the error message
checkCookie(); calls a function which has var username=getCookie("username");.
You haven't defined a getCookie function, so it throws an exception and stops execution.
I have tried to create a Javascript cookie in which I am creating and storing the cookie in browser and and checking if cookie is stored on Browser or not. If cookie is stored on browser it will return Welcome user Username otherwise it'll ask user to enter his name.
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;
}
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, 365);
}
}
}
<body onload= "checkCookie()">
<input type= "button" onclick= "checkCookie()" value= "val"/>
</body>
This code is prompting again and again to enter the cookie but not storing the cookie in browser
Please have a look at this and find a way to solve this problem?
Thanks
In this example I am to ask the user for their name via a prompt, then use the cookie to write to a div, "Welcome, savedCookie!" after entering and then each time they visit the page before the expiration.
I get the browser to present a prompt asking for my name and then it writes to the div as "Welcome, undefined!" I can't figure out why I receive the error.
//Setting cookie for Users Name
function set_it() {
var userName = prompt("Please Enter Your Name", ""),
thetext = "name=" + userName,
expdate = ";expires=Mon, 27 Mar 2017 13:00:00 UTC",
newtext = encodeURIComponent(thetext);
newtext += expdate;
document.cookie = newtext;
}
//Reading & Writing cookie
function read_it() {
var rawCookie = document.cookie;
bakedCookie = decodeURIComponent(rawCookie);
yumCookie = bakedCookie.split("=");
document.getElementById("greeting").innerHTML = "<p>Welcome, " + yumCookie[1] + "!</p>";
}
if (document.cookie) {
read_it();
} else {
set_it();
read_it();
}
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<div id="greeting">
<script src="prjs13_2.js"></script>
</div>
</body>
</html>
Try to run your only this code in console and look what you get-
var userName = prompt("Please Enter Your Name", ""),
thetext = "name=" + userName,
expdate = ";expires=Mon, 27 Mar 2017 13:00:00 UTC",
newtext = encodeURIComponent(thetext);
newtext += expdate;
document.cookie = newtext;
I did it for the name "david" and i got this-
name%3Ddavid;expires=Mon, 27 Mar 2017 13:00:00 UTC"
when you are setting your cookie your name attribute is not valid.
try this code instead (without encodeURIComponent and ; instead of comma)-
var userName = prompt("Please Enter Your Name", "");
var thetext = "name=" + userName;
var expdate = ";expires=Mon, 27 Mar 2017 13:00:00 UTC";
var newtext = thetext;
document.cookie = newtext;
You can use following function to get/set cookies:
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;
}
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, 365);
}
}
}
Here is some fiddle example: fiddle
I have two pages not popup. I want pass value from one to textbox in another one. And then close sender page.
If i use popup, I use this codes
My textbox in first page codes.
<input type="text" name="ModelTulID" id="ModelTulID"/>
Sender page's codes:
<input name="ModelID" type="hidden" value="<%=ID%>" />
<input type="button" value="Submit" onClick="sec()">
<script type="text/javascript">
function Sec() {
if (window.opener != null && !window.opener.closed) {
var txtName = window.opener.document.getElementById("ModelTulID");
txtName.value = document.getElementById("ModelID").value;
}
window.close();
}
But my pages are not popup and i don't know what i do. I tried window.top instead window.opener but it didn't work.
Thanks for your helps...
What you may want to take a look at is Javascript cross page cookies.
http://www.quirksmode.org/js/cookies.html
Set Get Cookie Demo
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=/";
}
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) {
createCookie(name, "", -1);
}
Using the common code for setting the username and password in cookie via javascript as below -
function submitLogin(){
var uNameInCookie=checkCookie("username");
var passInCookie=checkCookie("password");
if(uNameInCookie!=="" && passInCookie!=""){
document.loginForm.login.value=uNameInCookie;
document.loginForm.passwd.value=passInCookie;
document.loginForm.submit();
}
else{
if(checkInput()){
document.loginForm.submit();
}
}
}
function checkCookie(property){
var x= property;
var prop = getCookie(x);
return prop;
}
function getCookie(cName){
var name = cName + "=";
var cookiez = document.cookie.split(';');
for ( var i=0;i<cookiez.length;i++){
var c= cookiez[i].trim();
if(c.indexOf(name)==0){
return c.substring(name.length,c.length);
}
}
return ""
}
function checkInput()
{
if (document.loginForm.login.value == "")
{
return false;
}
else if (document.loginForm.passwd.value == "")
{
return false;
}
if (document.loginForm.login.value!= "" && document.loginForm.login.value!=null)
{
var usernameValue=document.loginForm.login.value;
setCookie("username",usernameValue,365);
}
if (document.loginForm.passwd.value!= "" && document.loginForm.passwd.value!=null)
{
var passwordValue=document.loginForm.passwd.value;
setCookie("password",passwordValue,365);
}
return true;
}
function setCookie ( cName, cValue, expDays){
var d = new Date();
d.setTime(d.getTime() + (expDays*24*60*60*1000));
var expDate = d.toGMTString();
alert(expDate);
document.cookie = cName + "=" + cValue + ";" + expDate + ";path=/";
}
window.onload=submitLogin();
</script>
the browser is able to auto login the details and submit the form only when I do a logout.
But if I close the browser and hit the url ,the username and password stored in cookie is gone and the form does not auto login.
Is there anything wrong with the code or is it some kind of browser setting. I have added the specific site also to add cookies if needed. Is there anything else that we need to do?
Thanks in advance.
The reason is when you are setting the cookie it's expiration date is not set and it's taking cookie for Session scope. Make correct the following line:
document.cookie = cName + "=" + cValue + "; expires=" + expDate + ";path=/";