Tuesday, January 1, 2013

Correct way to handle ajax forms

Just wondering what is the correct way to handle processing forms submitted via ajax / json response?

 

What I have been doing is converting my add / edit forms into a single element and placing them into the view/add/edit where needed so on error all I need to do is return the form element or on success whatever is needed success message.

 

In the controller :

 

if ( $this->Model->save($this->request->data, true)) {

                                                                                               

                $response = array(

                                'status' => true,

                                'html' => $this->render($this->autoElement('added_block'))->body(),

                                'message' => 'Saved!');

} else {

                                                                                               

                $this->set('errors', $this->Model->validationErrors);

                                $response = array(

                                                'status' => false,

                                                'html' => $this->render($this->autoElement('form'))->body(),

                                                'message' =>  'Please correct the following errors and try again!' );

}

$this->_ajaxReturn( $response ); //simply encodes $response array to json that gets passed to the js

 

This way the js can act according to the response status and has all the HTML info ready to drop into my <div> or where ever and has all the Cake inputs with errors. Is this going about it wrong? Or is there an easier way?

Just curious how others are approaching this.

 

Thanks,

 

Dave

No comments: