Jump to content

cookie example on w3schools not complete


gongpex

Recommended Posts

Hello everyone,

 

Today I tried to learn about js cookie on this page : cookie

 

on this tutorial there is only example about how to : set, get, and check cookie,

 

but there is no example to delete cookie.

 

I had try to create code to delete cookie like this :

function delCookie() {   var d = new Date();    d.setTime(d.getTime() + (exdays*24*60*60*1000));    var expires = "expires=" + d.toGMTString();    document.cookie = "username=;expires"; }

this code didn't work

 

and this my full code :

<!DOCTYPE html><html><head><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);       }    }}function delCookie() {   var d = new Date();    d.setTime(d.getTime() + (exdays*24*60*60*1000));    var expires = "expires=" + d.toGMTString();    document.cookie = "username=;expires"; }</script></head><body onload="checkCookie()"><button onclick="delCookie()">Delete cookie</button></body></html>

Q : what's mistake on my code?

 

OFFQ : I think this question is rather fool, but this is my first time use safari browser, if on firefox, chrome and IE press F12 to display debugger, how about on safari?

 

please someone help me

 

Thanks

Edited by gong
Link to comment
Share on other sites

so, I need to put the date like on example?

 

OFFQ : I think this question is rather fool, but this is my first time use safari browser, if on firefox, chrome and IE press F12 to display debugger, how about on safari?

 

please help

 

thanks

Link to comment
Share on other sites

A normal way to delete cookies is to change the expiry date to sometime in the past. That's how it's done in PHP. I'm not sure of the rules Javascript uses.

 

Here's the correction to the line of code I mentioned in the previous post.

document.cookie = "username=;" + expires;
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...