* Update on 2010-08-08: Please refer to Ajax implementation on CakePHP @ 3 for Ajax form in CakePHP.
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 // render the after_ajax_call.ctp $this->render('/elements/layout/after_ajax_call'); } }
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
<div id='ajaxDiv'> // 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' => <OPTIONAL - Ajax callback option for javascript>)); ?> <?php echo $form->end(); ?> </div>
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! =)
Hi,
thanks for this nice tutorial.
From my experience $ajax->submit() is not working in conjunction with $ajax->form().
The usual way is to use just the $form->submit() or $form->end(‘Submit’)
Best regards,
Eycke
LikeLike
Hi Eycke,
Thanks for your suggestion. actually the codes i mentioned above is just a result of trial and error.
hope this tutorial help =)
Kit
LikeLike