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
<script>
new Ajax.Request(
"url",
{
method: 'post',
parameters: {'val1': 1, 'val2': 2},
onComplete: displayResults
}
);
function displayResults(rsp)
{
var results = eval('('+rsp.responseText+')');
}
</script>


If response is the form of this
[
{"firstName":"Faheem","lastName":"Abbas","username":"fahim","email":"faheem.abbas@nxb.com.pk"},

{"firstName":"Shazil","lastName":"Hassan","username":"shazil","email":"shazil.hassan@yahoo.com"}
]


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.
<?php
class Users extends Zend_Db_Table
{
protected $_name = "users";
}


That's it. cheers.

1 comment: