Saving a complex JSON object in a cookie by using jQuery (demo included in PHP)

Saving a complex JSON object in a cookie by using jQuery (demo included in PHP)

Today, I spent almost three hours to test and implement a mechanism to save a complex JSON object and get it to render in a HTML output,, for this reason I would like to explain what was the best easiest way that I found for saving my object.

First, I would recommend you to be sure that your object is well-created, I mean, it is important that your JSON object is according to JavaScript Object Notation (you can visit this link to read more about: http://www.json.org/).

Second, I have used some compatible plugins with jQuery (I have tested this plugins using  jQuery 1.8.2, this because in my project jQuery had already existed, also I have tested in jQuery 1.10.2), In a nutshell, we need the next JavaScript files:

  1. jQuery
  2. jQuery Cookies
  3. JSON2

 Creating our complex JSON object

I have decided to use PHP to create our testing object (because most of developers have knowledge in this programming language).

// An array to simulate a complex JSON object
		$userSettings =  array(
			"personal_information" => array(
				"name" => "Alex",
				"last_name" => "Arriaga"
				),
			"extra_information" => array(
				"twitter" => "alex_arriaga_m",
				"facebook" => "alex.arriaga.m",
				"website" => "http://www.alex-arriaga.com/",
				"programming_languages" => array("HTML5", "CSS3", "JavaScript", "PHP", "Java", "C# .NET", "AWK", "LESS", "XML")
			)
		);

		// Creating the JSON object
		$jsonObject = json_encode($userSettings);

 Saving and getting our complex JSON object

Now, we can create a simple JavaScript code to save our JSON object and get it later.

	(function($){
		$(document).on('ready', function(){
			//A cookie by the name 'userSettings' now exists with a serialized copy of $userSettings
			$.cookies.set( 'userSettings', <?php echo $jsonObject; ?> );

			//A variable named 'userSettings' now holds the unserialized object, it should be identical to the PHP variable 'userSettings'
			var userSettings = $.cookies.get( 'userSettings' );

			// Do something with the values read from cookie
			console.log(userSettings);
		});
	})(jQuery);

Verifying result

To see the saved object please use Firebug (in cookie tab). See next images like a demo of this.

saving-json-object-in-cookie

Figure 1. Saving JSON object

getting-json-object-from-cookie

Figure 2. Getting JSON object and verifying in Firebug console

It is possible to configure several parameters, but I think is better for you read them in the official github page of this plugin: https://code.google.com/p/cookies/

You can download this example code for testing more parameters or personalize according to your project. Download here.

That’s it. Be happy with your code!

Alex Arriaga

  • Prev Post
  • Next Post