📜 ⬆️ ⬇️

AJAX in CakePHP on jQuery and Prototype

A small example of the implementation of AJAX in CakePHP, an example shows how easy it is to work with AJAX in SakePHP, the framework takes care of all the work. We implement an example on the jquery.js library, then we redo our example into the prototype.js library

Start

We need an installed and configured CakePHP framework.
image

Our example will consist of posts and comments to them, in the comments we will use AJAX technology.
Create tables posts and comments:
CREATE TABLE `comments` ( `id` varchar(36) COLLATE utf8_unicode_ci NOT NULL, `post_id` varchar(36) COLLATE utf8_unicode_ci NOT NULL, `title` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `body` text COLLATE utf8_unicode_ci, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; CREATE TABLE `posts` ( `id` varchar(36) COLLATE utf8_unicode_ci NOT NULL, `title` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `body` text COLLATE utf8_unicode_ci, `created` datetime DEFAULT NULL, `modified` datetime DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; 

')
We will provide all the “dirty” work to bake, namely using the cake bake command, the console application of the CakePHP framework (\ app \ Console \ cake), I generate a model, controller, and view of our application, bake will ask a couple of questions and automatically connect our models, set a check on the data entered into the model. The cake bake work is discussed in great detail in Chapter 8 “Using Shells: Get Further, Faster” of the book by Ahsanul Bari, Anupom Syam “CakePHP Application Development”.
image

We connect jQuery

You need to add the following line to the app \ View \ Layouts \ default.ctp file:
 echo $this->Html->script('jquery-1.8.3.min'); 

The library 'jquery-1.8.3.min.js' must be put in app \ webroot \ js \
Let us indicate to the helper of the CakePHP framework which of the JavaScript libraries we use, add the following to the app \ Controller \ AppController.php controller:
 public $helpers = array('Js' => array('Jquery'); 

But our application already uses the 'Html', 'Form', 'Session', 'Paginator' helpers, they were connected automatically, until we explicitly specified the helper, therefore we add them to the helper initializer:
 public $helpers = array('Html','Form','Session','Js' => array('Jquery'),'Paginator'); 


AJAX engine

Now the main code that will generate the AJAX engine.
 <div id="comments"> <!-- ,     AJAX--> <?php foreach($comments as $comment): ?> <div class="comment"> <!—  --> <p><b><?php echo $comment['Comment']['title'];?></b></p> <p><?php echo $comment['Comment']['body'];?></p> </div> <?php endforeach;?> <!--      --> <?php echo $this->Form->create('Comment',array('controller' =>'comments', action'=>'add','onSubmit'=>'return false;')); echo $this->Form->input('Comment.title'); echo $this->Form->input('Comment.body'); echo $this->Form->input('Comment.post_id',array('type'=>'hidden','value'=>$comment['Comment']['post_id'])); echo $this->Js->submit('Add Comment',array('url'=>'/comments/add_ajax','update'=>'#comments','evalScripts'=>'true')); echo $this->Js->writeBuffer(); //  echo $this->Form->end(); ?> </div> 

This code is placed in the existing app \ View \ Posts \ view.ctp file and a slightly modified code for reuse in the new app \ View \ Comments \ add_success.ctp file. The whole AJAX engine is placed in 3 lines, if you delete them, we get the usual input form:
 'onSubmit'=>'return false;' //  ,      echo $this->Js->submit('Add Comment',array('url'=>'/comments/add_ajax','update'=>'#comments','evalScripts'=>'true')); //   AJAX echo $this->Js->writeBuffer(); //CakePHP    JavaScript  

The $ this-> Js-> submit () function supports a lot of parameters, maybe you are going to get data from the server in JSON format or use the GET method. The details of the settings are here , but we are only interested in:
 'url'=>'/comments/add_ajax' //    ,       submit. 'update'=>'#comments', //     html ,     (#comments). 'evalScripts'=>'true' //    prototype,  AJAX      . 

If we run our example, we will see that CakePHP has already done all the work, namely, connected and configured the $ .ajax function of the jQuery library:
 <div class="submit"> <input id="submit-1030630577" type="submit" value="Add Comment"> </div> <script type="text/javascript"> //<![CDATA[ $(document).ready(function () {$("#submit-1030630577").bind("click", function (event) {$.ajax({data:$("#submit-1030630577").closest("form").serialize(), dataType:"html", evalScripts:"true", success:function (data, textStatus) {$("#comments").html(data);}, type:"post", url:"\/comments\/add_ajax"}); return false;});}); //]]> </script> 

image

Change jQuery to Prototype
Replace:
 //public $helpers = array('Html','Form','Session','Js' => array('Jquery'),'Paginator'); public $helpers = array('Html','Form','Session','Js' => array('Prototype'),'Paginator'); 

we will receive:
 <div class="submit"> <input id="submit-1936204617" type="submit" value="Add Comment"> </div> <script type="text/javascript"> //<![CDATA[ document.observe("dom:loaded", function (event) {$("submit-1936204617").observe("click", function (event) {event.stop(); var jsRequest = new Ajax.Updater("comments", "/comments/add_ajax", {evalScripts:"true", method:"post", parameters:$($("submit-1936204617").form).serialize()});});}); //]]> </script> 

image

if you correctly do the work on connecting the Prototype library:
 //echo $this->Html->script('jquery-1.8.3.min'); echo $this->Html->script('prototype'); 

, the application will already work on the Prototype engine.

AJAX button handler

The AJAX button handler is in the app \ Controller \ CommentsController.php controller
  public function add_ajax() { if ($this->request->is('post')) { $this->Comment->create(); if ($this->Comment->save($this->request->data)) { $comments=$this->Comment->find('all',array('conditions'=>array('post_id'=>$this->request->data['Comment']['post_id']),'recursive'=>-1)); $this->set(compact('comments')); $this->render('add_success','ajax'); } else { $this->render('add_failure','ajax'); } } } 

its description goes beyond the scope of the article I wanted to write; you can download the example discussed in this article here .

Bibliography:
John Reisig "JavaScript Professional Programming Techniques"
Benken E., Samkov G. “AJAX: Programming for the Internet”
Prokhorenok N. “jQuery New JavaScript Programming Style”
Prohorenok H. “HTML, JavaScript, PHP and MySQL. Gentleman Webmaster Kit
Jahnstorf Jason "PHP and jQuery for Professionals"
Michelle E. Davis, John A. Phillips "Learning PHP and MySQL"
David Flanagan “javascript. Detailed manual, 5th edition »
Mariano Iglesias "CakePHP 1.3 Application Development Cookbook"
David Golding "Beginning CakePHP From Novice to Professional"
Anupom Syam, Ahsanul Bari "CakePHP Application Development"
Kai Chan and John Omokore with Richard K. Miller "Practical CakePHP Projects"

Source: https://habr.com/ru/post/166653/


All Articles