How to manipulate cookie of array, object and json datatype using jQuery Plugins?

jquery_logo

A Cookie is a small amount of key value-based browser storage used to store tiny data on user’s browser by websites. It can be manipulated by JavaScript

Simple JavaScript code that manipulate cookie is

document.cookie = "key=value; expires=EXPIRY_TIME";

There are many jQuery plugins available to implement cookie easily with simple callbacks. That provides methods for add, remove or delete browser cookies.

  • $.cookie('key','value');
    $.cookie('key',['value1','value2'])
    $.cookie('key','{
                      "sub_key_1":"sub_value_1",
                      "sub_key_2":"sub_value_2"
                    }'
            );
  • // this cookie expires after 5 days
    $.cookie('key','value',{expires: 5});
    $.cookie('key',['value1','value2'], { expires: 5 });
    $.cookie('key','{
                      "sub_key_1":"sub_value_1",
                      "sub_key_2":"sub_value_2"
                    }'
                  , {
                    expires: 5
                    }          
            );
  • More options

    $.cookie('key','value'
                  , {
    		secure: true
                    }          
            );

    cross_domain_cookie

    Just prexif your domain value with dot (i.e. “.yourdomain.com”) in cookie option

    $.cookie('key','value'
                  , {
    				secure: true
                    }          
            );

    So above cookie is valid for all subdomain of site vikaskbh.com Check demo here

    Path defines scope of cookie. By default, cookies are being set to directory structure of url. i.e. if you are accessing http://www.example.com/directory and try to set cookie, it will be set to /directory path. You could set it to root directory path “/” with cookie path option.

    $.cookie('key','value'
                  , {
    				path: '/'
                    }          
            );
  • Reading cookie is simple, just pass cookie key to $.cookie() function.

    $.cookie('key');
    $.cookie('key').split(",");
    $.parseJSON($.cookie('key'));
  • To delete cookie, just use function $.removeCookie() and supply cookie key.

    $.removeCookie('key');
  • $.cookies.set('key');
    $.cookies.set('key',{
    	sub_key:'sub_value'
    });
  • $.cookies.get('key');
  • $.cookies.del('key');
Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

 
Previous Post

How to sort HTML table rows using different jQuery plugins?

Next Post

GeForce GTX graphics card DVI-VGA display converter doesn’t work – FIX

Related Posts