Thursday, 17 January 2013

Ajax with Json and prototype in Zend Framework | Zend Framework Tutorial

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;
    }
}

No comments: