Cookie Using JSON Format Javascript

Actually, some weeks ago, my senior made me create cookie using JSON format. Ok, keep calm, this is the first time, i create a cookie, i really blank about it πŸ˜€ haha the problem is using JSON format too..

I tried creating this cookie in java but the framework that i use, had a problem converting to json formatted cookie.

So, i use javascript instead πŸ˜€ and this one is really simple πŸ˜€

JSON result format should be, (sort by the newest data)

{"user":[{"name":"sunny","idcard":"88657890"},{"name":"ananti","idcard":"13456778"}]}

Below code is HTML.

Name : <input id="name" type="text" />
ID Card : <input id="idcard" type="text" />
<input onclick="setCookie('name','idcard',1)" type="button" value="Set Cookie" />


And this one is javascript.

	function setCookie(name,idcard,days) {
		var arr = new Array();
		var obj = new Object();

		//add new cookie data
		obj.name = document.getElementById(name).value;
		obj.idcard = document.getElementById(idcard).value;
		arr.push(obj);

		//get old cookie data
		var temp = getCookie();
		if (temp != null) {
			//concat new and old cookie data
			for (var i = 0; i < temp.length; i++) {
				var ob = new Object();
				ob.name = temp[i].name;
				ob.idcard = temp[i].idcard;
				arr.push(ob);
			}
		}
		var objWarp = new Object();
		objWarp.user = arr;
		var val = JSON.stringify(objWarp);

		//set cookie date expired
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
		//create cookie
		document.cookie = "user_cookie="+val+expires;
	}

	function getCookie() {
		var key,val,res;
		//get all cookie
		var oldCookie = document.cookie.split(';');
		for (var i = 0; i < oldCookie.length; i++) {
			key = oldCookie[i].substr(0,oldCookie[i].indexOf("="));
			val = oldCookie[i].substr(oldCookie[i].indexOf("=")+1);
			key = key.replace(/^\s+|\s+$/g,"");
			//find "user_cookie"
			if(key == "user_cookie") {
				res = val;
			}
		}
		if (res == undefined) {
			return null;
		} else {
			res = JSON.parse(res);
			return res.user;
		}
	}

simple, right? you should try it and make the modification on your own πŸ˜€

Cookie Using JSON Format Javascript

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s