Ajax implementation on CakePHP @ 1

I have been working on a website which make use of the ajax features under the CakePHP framework. Although the CakePHP framework provides Ajax Helper for the ajax implementation, it is not easy to use since there are not very much resources about cakePHP on web and some of them are quite confusing.

I just keep trial and error and finally make something work as i wish. =)

Simple Ajax Call

ExampleController.php
1. Include the necessary helper classes and component in the Controller

   var $helpers = array('Ajax', 'Javascript');
   var $components = array('RequestHandler');

2. Create the function for the initial page which has the ajax call

   function initialPage() {
      // do sth
   } 

3. Create the function for the loading the result of the ajax call

   function afterAjax() {
      // do sth
      $this->render('/elements/layout/after_ajax_call');
   } 

initial_page.ctp
4. Prepare the initial view before the ajax call

   <?php
      echo $javascript->link('prototype');
      echo $javascript->link('scriptaculous');
   ?>
   <div id='toBeReplaced'>
      Everything inside this div tag will be replaced by the response from the ajax function
   </div>
   <?php
      echo($ajax->link('do something ajaxy', '/{Controller}/afterAjax/', array('update'=>'toBeReplaced')));
   ?> 

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

   <?php
      echo('Your ajax call works!');
   ?>

Done!

Test the ajax after deployment. If the text is changed after clicking the do something ajaxy link. That means the your first CakePHP Ajax program is implemented successfully! Congradulations!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.