Ajax and Ajax Frameworks

I have been a developer for nearly 20 years and a web developer for about 10 years. Over the years, I have considered creating a blog to share the things I have learned (and am learning) about web design and development, but I never seemed to have the time. When I began learning about web development using Ajax and Ajax Frameworks, I decided to take the time to create this blog.

My intention for this blog is to focus primarily on Ajax Frameworks, but since web development requires knowledge of many technologies, I will occasionally write about things such as CSS, Javascript, PHP, MySQL, Flash, etc.

Lately, I have been using JQuery as my primary Ajax tool. Although I have used other Ajax Frameworks in the past (Dojo Toolkit, Yahoo! User Interface Library, Scriptaculous/Prototype), JQuery has thus far been the easiest to learn. In my first few posts I will discuss some of the JQuery Plugins that I have created. Some of these include: a plugin for Google Maps (jquery.imGoogleMaps), Form validation and submission  (jquery.imValidateForm), Page Populater (jquery.imPagePopulate), and a plugin to create lists (jquery.imList).

While I am still learning about some of the other Ajax Frameworks, I hope that what I have learned will be helpful to others. Just remember, “When you can pull the pebbles from my hand…”

Share

YAHOO.util.Connect, CakePHP, Json Data

Saturday, January 16th, 2010

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.

Share

One Response to “YAHOO.util.Connect, CakePHP, Json Data”

CommentLuv badge