Sunday 5 June 2011

JavaScript Cookies



Cookie: Cookie is a text file in client system, which is used to store some information. Cookies are divided into two types.
Inmemory Cookie:  A cookie without explicit expiry time is called as In memory Cookie. This cookie resides client Ram and destroys itself when client closes the website.
Persistent Cookie : If we create any cookie with expiry date , it comes under persistent cookie. It resides client Hard disk and destroys with the help of operating system when the expiry time is reached.
Persistent Cookie stores in a text file within the browser buffer memory.
*In JavaScript using document.cookie, we can create the cookies and we can also read the cookies.
In memory cookie:
Sample Script :
<script>
document.cookie="Script=Danphp JavaScript"
document.cookie="Tutorial=PHP Notes"
alert(document.cookie)
</script>
Persistence Cookie:
Sample Script:
<script>
var d=new Date()
d.set Time(d.getTime()+3600*1000*24*365)
document.cookie="con1=ind; expires="td.toGMTString()
</script>

Sample Script :
<script>
function readCookie()
{
document.getElementByid("txtpwd") value=""
str=document.cookie
uname=document.getElementByid('txtuname').value
arr=str.split(";")
for(i=0;i<arr.lenght;i++)
{
newarr=arr[i].split("=")
if(newarr[0]==uname)
document.getElementByid('txtpwd').value=newarr[1]
}}
function fun()
{
if document.getElementBid('chk1').checked
{
uname=document.getElementByid('txtuname').value
pwd=docuemnt.getElementByid('txtpwd').value
d=new Date()
d.setTime(d.getTime()+3600*1000*2)
str=uname+"="pwd+"; expires="+d.+GMTString()
document.cookie=str
alert(document.cookie)
}}
</script>
<table bgcolor="blue">
<tr><td>Uesername</td><td><input type="text" id="txtuname" onblur="readCookie"()></tr>
<tr><td>Password</td><td><input type="password" id="txtpwd"></td></tr>
<tr><td colspan="2"><input type="checkbox" id="chk1">Remember</tr></td>
<input type="button" value="Login" onclick="fun1()"</table>



0 comments:

Post a Comment