Sunday, November 4, 2012

Re: CakePHP 2.x and ajax

The ajax helper is deprecated in 2.0.

Here's a quick and dirty ajax form submission:

in app_controller->beforeFilter():

if ($this->RequestHandler->isAjax()) {
     Configure::write('debug', 0);
     $this->autoRender = false;
     $this->layout = 'ajax';
}

In the <head> section of default layout:

<script>
     var baseUrl = "<?php echo $this->Html->url('/', true); ?>";
</script>

At the end of the controller function (after all variables have been set):

if ($this->RequestHandler->isAjax()) {
     $this->render('/elements/[element name]);
}


At the foot of the form containing the form to submit via ajax (or in an external js file that's called with $this->Html->script):

<script>
     $('#[FORM_NAME]').submit(function() {

          $.ajax({
               type: 'POST',
               url: baseUrl + '[ROUTE]', - note that baseUrl has a following / so no need to put one in from of [ROUTE]
               data: $(this).serialize(),
               dataType: 'html',
               success: function(data){
                    $('#[id of receiving content]').fadeOut(100, function() {
                         $(this).html(data).fadeIn(500);
                    });
               },
               error: function(message){
                    console.debug(message);
               }
          });
     return false;
     });

</script>

And that's it!!


On 4 Nov 2012, at 06:59, kani <infokani@gmail.com> wrote:

http://www.cakephp.4uk.pl

On Thursday, November 1, 2012 4:18:57 PM UTC+8, franscelstain wrote:
is there someone who can teach me to use ajax in cakephp 2.x, because I am still very novice

thanks

--
Like Us on FaceBook https://www.facebook.com/CakePHP
Find us on Twitter http://twitter.com/CakePHP
 
---
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To post to this group, send email to cake-php@googlegroups.com.
To unsubscribe from this group, send email to cake-php+unsubscribe@googlegroups.com.
Visit this group at http://groups.google.com/group/cake-php?hl=en.
 
 

No comments: