0

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


If response is the form of this

[
{"firstName":"Faheem","lastName":"Abbas","username":"fahim","email":"faheem.abbas@example.com"},

{"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.

class Users extends Zend_Db_Table
{
    protected $_name = "users";
}

That’s it. cheers.

Filed in: JSON, Zend Framewrork Tags: , ,

Leave a Reply

Submit Comment

© 9628 Faheem Abbas. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
Top Footer