Sunday, July 5, 2009

Ajax with Json and prototype in Zend Framework

I used JSon for the first time in my application today. Zend provide a very easy way to create JSon response.
In this article I would use Prototype to make ajax call. Hopefully you will now a bit about Prototype. Anyway if not, it would not be a hard job to understand it after reading my article.
So let’s get started.
Consider you have the following form.


The scenario is
When user select name from the dropdown, the entire form is filled with the data from the database for that particular user.

For this purpose you would need to have a controller/Action(s), a model and template file.
In your form attach the following attrib to your name element as

<?php
$name = $this->createElement('select','name');
$name->addMultioptions(array(
'select'=>'[select]',
'1' => 'Faheem',
'2' => 'Abbas'
));

$name->setAttrib('onchange','AutoFill()');

In the lines above we first create a dropdown give it two values. And then attach javascript function “AutoFill” function using setAttrib method.

In your controller initialize your form and assign it to the view template as
$form = new MyCustomForm();
$this->view->form = $form;

Now in your view template file write the following.
Write the following javascript code.
<script>
function AutoFill()
{
new Ajax.Request(
"<?=$this->url(array('controller'=>'user','action'=>'getdata'))?>",
{
method:'get',
parameters: {id: value},
onSuccess: FillForm
}
}

function FillForm(rsp)
{
var card = eval('(' + rsp.responseText + ')');
$('address1').value = card.items[0].address1;
$('address2').value = card.items[0].address2;
$('postalcode').value = card.items[0].postalcode;
}
</script>

To get response you will need to create an action and write the following code
<?php
class User extends Zend_Controller_Action
{
public function indexAction()
{
$form = new MyCustomForm();
$this->view->form = $form;
}

public function getdataAction()
{
$this->_helper->layout()->disableLayout();
$users = new Users();

$this->_helper->viewRenderer->setNoRender();
if ($this->getRequest()->isXmlHttpRequest()) {
$id = $this->_getParam('id');
$userData = $ users ->getData($id);
$dojoData= new Zend_Dojo_Data('id',$userData,'id');
echo $dojoData->toJson();
}
}
}

In the above code getdataAction is called using ajax call. In the first line we have disabled the layout, because we don’t need layout in case of ajax response. Next we create object of our model class(discussed later). Next we tell zend to disable view rendering.
In the next few lines we check for ajax request, get id, call our getData model method.
We then create dojo data object. This object provide a very useful method to convert data retrieved into json format. The method used is toJson().

In our model we have code like the following.
<?php
class Users extends Zend_Db_Table
{
protected $_name = 'users';

public function getData($id)
{
$select = $this->_db->select()
->from($this->_name,
array('address1','address2'….))
->where('id = ?', $id);
$result = $this->getAdapter()->fetchAll($select);
return $result;
}
}


That's it. Cheers.

12 comments:

  1. public function getData($id)
    {
    $select = $this->_db->select()
    ->from($this->_name,
    array('address1','address2'….))
    ->where('id = ?', $id);

    ReplyDelete
  2. this is exactly what i needed as a reference... thanks.

    Smith | spa uniforms

    ReplyDelete
  3. Guys! I've a lot of problems with this example! I can't make my code function! I'm newbie about zend and prototype together. Has anyone the possibility to explain me the initial settings of prototype? Can you say me if some variable or settings in this example are only for demonstration and are setted with trial values or are "official"? During the debugging I realized that the problem could be the Ajax.Request function. Say me something, please!!!!! I'm desperate!!! (P.S. I've some doubts with $dojoData= new Zend_Dojo_Data('id',$userData,'id'), why 'id'!? Is the id of the form or of the form element!?!?

    ReplyDelete
  4. Thanks, It really works.

    ReplyDelete
  5. @Anonymous glad u made it work :)

    ReplyDelete
  6. Business Logo Design |
    I would agree that sketching ought to be a vital part of any design project, and that it is liberating and effective for getting superior concepts down swiftly on paper. I find it precious for my design practice and always support other designers to get excellent sketchbooks and pencils, so they can construct drawing an integral part of their own design processes. Thanks a lot.

    ReplyDelete
  7. Hi,

    Iam new to Zend Framework.For this above example, what version of jquery should be used. Can you give me the full code of view script file?

    ReplyDelete
  8. Hi,

    good information

    Web application development services will successfully change the execution of your online business So, hire our skilled Ecommerce website company to get customized applications for your business.

    Best Website Designing and Development Company
    "
    Ecommerce Website Development Company
    "
    Zend Framework

    ReplyDelete