Ben
Ben

Reputation: 25807

How make Zend_Form submission without reload a page - with Ajax?

How make Zend_Form submission without reload a page - with Ajax?

This is code for create form that reload a page when submitted, what should be change or add that this form will submit with ajax (1.regular solution 2.jquery solution):

Form:

class Application_Form_Login extends Zend_Form
{
    public function init()
    {
       $username=new Zend_Form_Element_Text('username');
       $username ->addFilter('StringToLower')
                 ->addValidator('alnum');
       $password=new Zend_Form_Element_Text('password');
       $password->addFilter('StringToLower')
                ->addValidator('alnum');
       $submit=new Zend_Form_Element_Submit('submit');
       $this->addElements(array($username,$password,$submit));
    }
}

Controller:

$form = new Application_Form_Login();
        $request = $this->getRequest();
        if ($request->isPost()) {
            if ($form->isValid($request->getPost())) {
                if ($this->_process($form->getValues())) {
                    //code indside
                }
            }
        }
$this->view->form = $form;

View:

<?
echo $this->form;
?>


My proposal that I don't think is proper(does form make filtering and validation?) for View:

<?
echo $this->form;
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $('form').submit(function(){
      var sendData=$(this).serialize();
            $.ajax(
                        {
                           url:'',
                           dataType:'json',
                           type:'POST',
                           data:sendData,
                           success: function(data) {                   
                           }
                       });
         return false;
    });
});
</script>

Thanks

Upvotes: 1

Views: 2070

Answers (1)

Henrique Vicente
Henrique Vicente

Reputation: 225

Well, for filtering/validation you might want to send the form using Ajax and by knowing at the server-side that it is an Ajax request (you can use a flag for that, like a header, search for knowing if a request is ajax or not) and sending back only the form 'area'. Then when you receive it you can overwrite it.

There is currently no wiser way to do it with Zend_Form I think.

Upvotes: 1

Related Questions