I haven’t seen much tutorials around explaining using JSON with mootools, so I decided to write one. A year ago I always thought JSON’s a hard to understand way to have your client apps communicate with a server. Well, by using mootools it’s a breeze. If you don’t know what JSON is, check out json.org. Json.org says the following about JSON:

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate.

So keywords are lightweight and easy writing/parsing. The following image might clear things up.


So basically JSON works like this: you encode a javascript object to a JSON string. Using some ajax magic (xhr) you can send this string to the server. On the server you can use Service_JSON to decode your JSON string to a PHP object and do some actions on the object. In the Json.toString({day: ‘monday’, month: ‘December’})same way we can parse a PHP object to a JSON string and send it back to the client. There the string is parsed to a Javascript object so we can use it again. Great idea huh?

This tutorial uses a server-side script written in PHP, but all kinds of server-side languages have the ability to parse/generate JSON. Michal Migurski has written the ‘Services_JSON‘ class that let’s you easily encode and decode JSON strings. Whe’re going to use that class, in combination with the following mootools modules:

  • Main lib: mootools.js
  • Native scripts: String.js, Array.js, Function.js and Element.js
  • Addons: Ajax.js
  • Plugins: Json.js (from svn)

Setting up the environment

Go to the mootools download page and download the modules. Make sure you get the mootools Json module from svn. To reduce the filesize you can enable high compression. I usually don’t compress the file when I’m making a tutorial like this one. This way I can look in the source code how methods work and which arguments they take, without looking into the mootools documentation. When I use a script on a website that has lots of visitors it’s better to use the compressed version, because then there’s no need to check the source code.
Place the JSON.php file in the same directory.

Javascript JSON encoding/decoding

Mootools makes JSON encoding/decoding very easy. The Json.js module gives us just two methods called Json.toString(object) and Json.evaluate(object). The first function encodes a Javascript object to a JSON string, and the second decodes a JSON string to a Javascript object. The following code illustrates the functionality:

Json.toString({day: 'monday', month: 'December'}) // => {"day":"monday","month":"December"}
Json.toString(['1','2']) // => ["1","2"]

PHP JSON encoding/decoding

To do something with the JSON sent to the server we need a JSON parser. In this example I use ‘Services_JSON‘. The following code show how to use it.


	//make a new json parser
	$json = new Services_JSON;

	//decode incoming JSON string
	$jsonRequest = $json->decode(file_get_contents(\'php://input\'));

	//change day	
	$jsonRequest->day = \'tuesday\';

	//change weather 	
	$jsonRequest->weather = \'sun\';

	//echo the changed jsonRequest
	echo $json->encode($jsonRequest);

You can see a working example at example page 1.

Advanced JSON usage

This is what I learned while I was using the Dojo Toolkit. This is really handy. It’s possible to send JSON to the server and with a function name and a parameter. The server-side script then executes the function with the specified name with the given parameter. The javascript code will look something like this:

window.onload = function(){
	var jsonString = Json.toString({method: 'nextDay', params: 'monday'});
	$('sendJSON').innerHTML = jsonString;
	new ajax('./jsonservice2.php', {postBody: jsonString, onComplete: function(req){$('returnJSON').innerHTML = req;}}).request();

This code assumes there’s a function called 'nextDay' in the ‘jsonservice2.php’ file. This function’ll be called with the parameter ‘monday’. The result will be ‘tuesday’. This is the PHP code:

	class foo{
		//return next day
		function nextDay($day){
			switch ($day){
				case \'monday\': return \'tuesday\';
				case \'tuesday\': return \'wensday\';
				case \'wensday\': return \'thursday\';
				case \'thursday\': return \'friday\';
				case \'friday\': return \'saturday\';
				case \'saturday\': return \'sunday\';				
		//adjust the weather	
		function adjustWeather($weather){
			if($weather == \'rain\') return \'sun\';
			else return \'rain\';

	//object to return
	$results = array();

	//make a new json parser
	$json = new Services_JSON;

	//decode incoming JSON string	
	$jsonRequest = $json->decode(file_get_contents(\'php://input\'));	

	//some php magic that calls a method with the given parameter from a newly created foo object
	$results[\'result\'] = call_user_func_array(array(new foo(),$jsonRequest->method),$jsonRequest->params);

	//remember the method that is called
	$results[\'method\'] = $jsonRequest->method;

	//remember the parameter(s)
	$results[\'params\'] = $jsonRequest->params;

	//echo the changed jsonRequest
	echo $json->encode($results);	

You can see this code working on example page 2. As you can see JSON is a great way to communicate with the server. Especially when you have an application that does a lot of communication with the server. When you have a small application you’d better use the normal HTTP GET or POST methods.

I hope this was enough for you to understand the way of using JSON with mootools and PHP. Enjoy the code.
If you have any further questions please ask.