Click here to Skip to main content
15,916,692 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
How to access cookie value declared in a server side in javascript?
JavaScript
Response.Cookies["StudentCookies"].Value="SOME VALUE"

Now i want to access this Cookies value in javascript
Please suggest
Posted
Updated 26-Dec-11 5:08am
v2

Use the 'document.cookie' JavaScript property to access the cookie.

MSDN help[^]

This similar post[^] would help you.
 
Share this answer
 
v2
For example you want to get the cookie value on button client click even:
ASP.NET
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="GetCookie('StudentCookies')" />

Use following script within head tag:
JavaScript
<script type="text/javascript">
    function GetCookieValue(check_name) {
        var a_all_cookies = document.cookie.split(';');
        var a_temp_cookie = '';
        var cookie_name = '';
        var cookie_value = '';
        var b_cookie_found = false; // set boolean t/f default f

        for (i = 0; i < a_all_cookies.length; i++) {
            // now we'll split apart each name=value pair
            a_temp_cookie = a_all_cookies[i].split('=');
            // and trim left/right whitespace while we're at it
            cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
            // if the extracted name matches passed check_name
            if (cookie_name == check_name) {
                b_cookie_found = true;
                // we need to handle case where cookie has no value but exists (no = sign, that is):
                if (a_temp_cookie.length > 1) {
     cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
                }
                // note that in cases where cookie is initialized but no value, null is returned
                alert(cookie_value);
                break;
            }
            a_temp_cookie = null;
            cookie_name = '';
        }
        if (!b_cookie_found) {
            alert('No data Found');
        }
    }
</script>
 
Share this answer
 
v2
Hi use below function to get cookie in javascript

JavaScript
function GetCookie (name) {
  var arg = name + "=";
  var alen = arg.length;
  var clen = document.cookie.length;
  var i = 0;
  while (i < clen) {
    var j = i + alen;
    if (document.cookie.substring(i, j) == arg) {
      return getCookieVal (j);
      }
    i = document.cookie.indexOf(" ", i) + 1;
    if (i == 0) break;
    }
  return null;
  }


JavaScript
if (GetCookie('user_id') == null) {

//Write your code here
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900