How To Manipulate Cookies With JQuery

When developing web applications you sometimes need to keep track of some things on the clients computer cookies can help you achieve that. A Cookie is a small text based file given to you by a visited website that helps identify you to that site. Cookies are used to maintain state information as you navigate different pages on a Web site or return to the Web site at a later time.

In this post i will show you how to create, retrieve, delete and generally how to manipulate a cookie using jquery. To do this there is already a jquery plugin (jquery cookie) that greatly simplifies this process. Download the plugin and reference it after you have referenced your jquery because the plugin requires jquery to work.

Now we can get our hands dirty and play with cookies

CREATING (SETTING) A COOKIE

  • Create a session cookie
    $.cookie('name', 'john doe');
    //creates a cookie called name and assigns the value 'john doe' to it
    

  • Create a session cookie that expires in day(s)
    $.cookie('name', 'john doe',{ expires: 5 });
    //creates a cookie called name and assigns the value 'john doe' to it 
    //and the cookie expires in 5 days
    

  • Create a session cookie that expires in minutes(s)
    //Getting the current date and time
    var tenMinsAhead = new Date();
    
    //Converting 10mins to milliseconds
    var minOffset = 10*60*1000;
    
    //adding 10mins to current time
    tenMinsAhead.setTime(tenMinsAhead.getTime() + tenMinsAhead);
    
    $.cookie('name', 'john doe',{ expires: tenMinsAhead });
    //creates a cookie called name and assigns the value 'john doe' to it 
    //then sets the cookie expires 10 minutes to the time it was created
    

RETRIEVING (GETTING) A COOKIE

  • Retrieve a session cookie
    $.cookie('name', 'John Doe');
    $.cookie('age', '150');
    $.cookie('location', 'Lagos Nigeria');
    
    //Retrieve a particular session cookie
    $.cookie('name');//=> John Doe
    
    //Retrieve all available session cookies
    $.cookie();//=> { "name": "John Doe","age": "150","location", "Lagos Nigeria" } 

DELETING A COOKIE

  • Delete a session cookie
    // Returns true when cookie was successfully deleted, otherwise false
    $.removeCookie('name'); // => true
    $.removeCookie('nothing'); // => false
    

0 comments :