Sunday, July 12, 2009

Implementing Ajax with Zend Framework and Json

Well, while working with ajax, it better to have an xml as response. Xml, however need more coding and parsing on client side than json.
Zend framework provides very easy way to generate json response.
In this article I’m going to discuss how to create Ajax request using prototype and how to use Zend_Json to generate response.
For generating Ajax request, you will need to write
new Ajax.Request(
method: 'post',
parameters: {'val1': 1, 'val2': 2},
onComplete: displayResults
function displayResults(rsp)
var results = eval('('+rsp.responseText+')');

If response is the form of this


Then to acess the values of the first row, write
var firstName = results[0].firstName;
var lastName = results[0].lastName;

and the values of the second row can be accessed as
var firstName = results[1]. firstName;
var lastName = results[1].lastName;

To create Json response, you will need to write the following in your controller action
$users = new Users();
$username = $this->_getParam('username');
$select = $users->select();
$data = $users->fetchAll($select);
$results = $data->toArray();
echo Zend_Json::encode($results);

Keep in mind that “users” is our model, having the following code.
class Users extends Zend_Db_Table
protected $_name = "users";

That's it. cheers.

1 comment:

  1. Security Logo Design
    Last year I have worked with some random e-firm and from then my distrust have developed. But now I can proudly say that if you find some talented team your perception switch just mine does after working with you guys. Best of luck!!!