user2818060
user2818060

Reputation: 845

how to get value from cookie in javascript

What i Need:

code i have tried :

function setCookie(key, value) {  
var expires = new Date();  
expires.setTime(expires.getTime() + 31536000000); //1 year  
document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();

}  

   function getCookie(key) {  
     var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');

     return keyValue ? keyValue[2] : null;  
       }  

    setCookie('evnt_id','evnt_id');  
   alert(getCookie('evnt_id')); 

Upvotes: 1

Views: 2223

Answers (1)

James Hibbard
James Hibbard

Reputation: 17795

This problem has been solved before. Don't reinvent the wheel :)

I would advise you to read up on cookies: http://www.quirksmode.org/js/cookies.html

The code below comes from that article.

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

console.log(readCookie('evnt_id'));  //9
console.log(readCookie('user'));     //13530767

Upvotes: 2

Related Questions