Jump to content

How to set cookies in javascript file


Recommended Posts

I always use php to set a cookie but I had this example from a long time ago. Also you need to rememeber if they have thier javascript turned off in thier browser it won't work, but with php it will.

 

http://byrondallas.heliohost.org/java/if_s...ent-cookie.html

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
<title>Untitled Document</title>
<script type="text/javascript">
// set cookie
document.cookie="cookiename="playsong";

//" get only cookie name
function get_cookie ( cookiename ) {
  var results = document.cookie.match ( '(^|;) ?' + cookiename + '=([^;]*)(;|$)' );
  if ( results )
        return ( unescape ( results[2] ) ); else 
        return null;
}
</script>
</head>
<body text="#000000" bgcolor="#FFFFFF">

<script language="JavaScript">
var cookie_text = get_cookie ( "cookiename" );
document.write("The Cookie name is ");
document.write(cookie_text);

document.write("<p>");

if (cookie_text == 'playsong')
{
document.write("<b>Hello World!</b>");
}
else
{
document.write("<b>CODE IF COOKIE DOES NOT EXIST</b>");
}
</script>

</body>
</html>

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...