Ajax implementation on CakePHP @ 2

An ajax call which only replaces the text may not be what u want to do. Here is the sample code of an ajax form in CakePHP.

Ajax Form
1. Included the necessary helpers and component in the Controller
2. Create a before-submission-form function to render the initial form view
3. Create a after-submission-form to render the web content after the ajax call
4. Here is an example controller

<?php
Class AjaxController extends AppController {
var $name = 'Ajax';
var $helpers = array('Form','Html','Javascript', 'Ajax');
var $components = array('RequestHandler');

function beforeAjaxAction() {
// do sth before rendering the before_ajax_action.ctp
}

function afterAjaxAction () {
// get the $this->data to collect the form information
// save the object to database
}
}

5. Prepare the before_ajax_action.ctp

  • model is the database model which will saves the form data
  • ajaxDiv is the div which will be updated after the ajax call
  • form_id is the form id for javascript
  • url refers to the location of the beforeVoteAjax function and afterVoteAjax function

// create the form
<?php
echo $ajax->form(array('type' => 'post',
'options' => array('model' => 'model',
'update' => 'ajaxDiv',
'id' => 'form_id',
'url' => array('controller' => 'AjaxController',
'action' => 'beforeVoteAjax'))));
?>
<?php echo $form->input(...); ?>
<?php echo $form->input(...); ?>
<?php echo $form->input(...); ?>
<?php echo $ajax->submit('Submit', array('url' => '/ajax_controller/afterAjaxAction', 'update'=>'ajaxDiv', 'before' => )); ?>
<?php echo $form->end(); ?>

6. Prepare the content after the ajax call – ~/elements/layout/after_ajax_call.ctp

<?php echo 'Your ajax call works!' ?>

7. Test your ajax form
8. Done! =)
Posted in CakePHP Tagged: AJAX, CakePHP