YAHOO.util.Connect, CakePHP, Json Data

I’ve been upgrading an Intranet application that I created for a client. I created the front-end using YUI (Yahoo! User Interface Library) and I am working on migrating the back-end to CakePHP. After setting up CakePHP, my first step of integrating YUI with CakePHP is retrieving data ajaxally. The application was already using YAHOO.util.Connect to retrieve the data, but I had to change my parsing code due to the format of the Json data that is returned by CakePHP.

The CakePHP Controller

First we’ll setup the controller. We need to add the Javascript Helper and the RequestHandler Component.

var $helpers = array('Javascript');
var $components = array('RequestHandler');

Next we create a controller method. Let’s say that we want method that retrieves all language id’s and descriptions from the Language controller.

function getLanguages() {
        // set autoRender to false for Ajax requests
	$this->autoRender = false;
        // set debug to 0 so debug information is not sent back to the application
	Configure::write('debug', 0);
	$result = $this->Language->find('all', array('fields' => array('Language.id', 'Language.name'), 'recursive' => -1));
	return json_encode($result);
}

I’m using CakePHP’s find method with type ‘all’. The important thing to notice the recursive option. If I don’t set the recursive option to -1, then find all will retrieve more than just language data. It will also retrieve all associated model data.

Also notice that I am using json_encode. I attempted to use CakePHP’s Javascript Object method, but after an hour of trying to return a result, I moved on.

$javascript->object($result);

Normally when I deal with Json data from a database query, I am used to seeing it in the following format:

?View Code JAVASCRIPT
[{"id" :  "1", "name":  "Afrikaans"}, {"id" :  "2", "name":  "Albanian"}, {"id": "3", "name": "Amharic"}]

But the format created by CakePHP’s find all (after json encoding), looks like the following:

?View Code JAVASCRIPT
[{"Language" : {"id": "1", "name": "Afrikaans"}},{"Language":{"id": "2", "name": "Albanian"}},{"Language": {"id": "3", "name": "Amharic"}}]

This format will be important to remember when we parse the data using YUI.

YUI – YAHOO.util.Connect

Ok, now comes the fun. First we use YAHOO.util.Connect to retrieve the json data from the Language controller method.

?View Code JAVASCRIPT
var request = YAHOO.util.Connect.asyncRequest('GET', 'Language/getLanguages', callback);

We’ll create a simple callback method.

?View Code JAVASCRIPT
var callback =	{
  	success:handleSuccess,
  	failure:handleFailure
};

Now we handle success and failure:

?View Code JAVASCRIPT
var handleFailure = function(o){
// do something			
}
 
var handleSuccess = function(o){
	var response = [];
 
	if (o.responseText !== undefined) {
		try {
                        // parse the json data
	                response = YAHOO.lang.JSON.parse(o.responseText);
	            }
	            catch (x) {
	                alert("JSON Parse failed! " + o.responseText);
	                return;
	            }
                // get the number of records
		var nL = response.length;
                // iterate through the data
		for (var i=0; i<nL; i++) {
                        // get language id
			console.log(response[i]['Language']['id']);
                        // get Language name
                        console.log(response[i]['Language']['name']);
		}
	}
}

Remember each Json record is formatted with the controller name:

?View Code JAVASCRIPT
{"Language" : {"id": "1", "name": "Afrikaans"}}

So

?View Code JAVASCRIPT
response[i] = {"Language" : {"id": "1", "name": "Afrikaans"}}
 
response[i]['Language'] = {"id": "1", "name": "Afrikaans"}
 
response[i]['Language']['id'] = 1

Now I could have used dot notation to retrieve the data:

?View Code JAVASCRIPT
response[i].Language.id

Whatever floats your boat. That’s it. So as you can see using YUI (YAHOO.util.Connect) to retrieve Json data returned from CakePHP is not that difficult. Enjoy.

Be Sociable, Share!

Checkout My New Site - T-shirts For Geeks