Saturday, January 28, 2012

Cookis in JavaScript


JavaScript Code:
<script language="javascript" type="text/javascript">

    function getCookieValue(offset)
    {
        var endstring = document.cookie.indexOf(";", offset);
        if (endstring == -1)
        {
            endstring = document.cookie.length;
            return unescape(document.cookie.substring(offset, endstring));
        }
    }

    function getcookie(name) {
        var arg = name + ":";
        var strlength = arg.length;
        var cookielength = document.cookie.length;
        var i = 0;
        while (i < cookielength) {
            var j = i + strlength;
            if (document.cookie.substring(i, j) == arg)
            {
                return getCookieValue(j);
                i = document.cookie.indexOf(" ", i) + 1;
            }
            if (i == 0)
            {
                break;
            }
        }
        return null;
    }

    function setcookie(name, value)
    {
        var argv = setcookie.arguments;
        var argc = setcookie.arguments.length;
        var expires = (argc > 2) ? argv[2] : null;
        var path = (argc > 3) ? argv[3] : null;
        var domain = (argc > 4) ? argv[4] : null;
        var secure = (argc > 5) ? argv[5] : false;
        document.cookie = name + "=" + escape(value) +
        ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
        ((path == null) ? "" : ("; path=" + path)) +
        ((domain == null) ? "" : ("; domain=" + domain)) +
        ((secure == true) ? "; secure" : "");
    }

    function DeleteCookie(name) {
        var exp = new Date();
        exp.setTime(exp.getTime() - 1);
        var cval = getcookie(name);
        document.cookie = name + ":" + cval + "; expires=" + exp.toGMTString();
    }

    function shows() {
        if (getcookie('Demoname') == null)
        {
            alert('Did you submit the request?');
        }
        else
        {
            window.open('open.htm', '_top');
        }
    }
</script>

HTML Code:
 <form name="FormID" onSubmit="
    if(FormID.Username.value.length != 0) {
        var expdate = new Date();
        expdate.setTime(expdate.getTime() + (24 * 60 * 60 * 1000));
        setcookie('FormID', FormID.Username.value, expdate);
        alert('Enter here!!');
        return false;
    } else {
        alert('You left the name field blank!!');
        return false;
    }">

    <input type="text" name="Username" /><br />
    <input type="submit" value="Submit the Request!" /></br>
    <input type="button" value="Enter here!" onClick="this.shows()" />

</form>

No comments: