Click here to Skip to main content
14,635,442 members
Rate this:
Please Sign up or sign in to vote.
See more:
How to access cookie value declared in a server side in 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
Rate this:
Please Sign up or sign in to vote.

Solution 1

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

MSDN help[^]

This similar post[^] would help you.
   
v2
Rate this:
Please Sign up or sign in to vote.

Solution 2

For example you want to get the cookie value on button client click even:
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="GetCookie('StudentCookies')" />

Use following script within head tag:
<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>
   
v2
Rate this:
Please Sign up or sign in to vote.

Solution 3

Hi use below function to get cookie in 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;
  }


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

//Write your code here
}
   
v2

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




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100