Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simple ajax example with cakephp 2.3.0

Tags:

ajax

cakephp

please help me, if anyone can give me an example how to use ajax with cakephp 2.3.0 an example is like this

<?php echo $this->html->link('Original', '#', 
                array('onclick'=>'return false;', 'id'=>'remanufactured-link', 'class'=>'get-type-product-link')); ?>   

<div id="content">
</div>

when i click a original link a div with id content is change. how can i do it this with cakephp 2.3.0?

like image 257
casper Avatar asked Feb 08 '13 08:02

casper


3 Answers

See below example:

         $.ajax({
            dataType: "html",
            type: "POST",
            evalScripts: true,
            url: '<?php echo Router::url(array('controller'=>'your-controller','action'=>'your-action'));?>',
            data: ({type:'original'}),
            success: function (data, textStatus){
                $("#div1").html(data);

            }
        });
like image 40
Vijay Choudhary Avatar answered Nov 14 '22 23:11

Vijay Choudhary


There's not much difference to using CakePHP with Ajax than with regular HTML/PHP and Ajax.

Here's an example of an ajax call and response in a Cake APP:

jQuery:

$.ajax({
    url: '/types/fetch/original',
    cache: false,
    type: 'GET',
    dataType: 'HTML',
    success: function (data) {
        $('#context').html(data);
    }
});

(Don't forget to change the url parameter to match your setup).

This will make an ajax request to your Types controller and call the method fetch() with the parameter 'original'.

Your TypesController would look something like this:

class TypesController extends AppController {

    public $components = array(
        'RequestHandler'
    );

    public function fetch($type) {

        $data = $this->Type->find('all', array(
            'conditions'=>array(
                'Type.type'=>$type
            )
        );

        $this->set('data', $data);

    }
}

Adding the RequestHandler component means Cake will automatically use the minimal Ajax layout when rendering your Ajax requests. Usually this is added in AppController so all Controllers can use it.

And the associated view:

/app/View/Types/fetch.ctp

<ul>
    <?php foreach($data as $item): ?>
    <li><?php echo $item['Type']['name']; ?></li>
    <?php endforeach; ?>
</ul>
like image 70
RichardAtHome Avatar answered Nov 14 '22 21:11

RichardAtHome


I just started myself with cakePHP and Ajax, but from what I gathered so far this seems the easier approach. In your view use:

echo $this->Js->link(
    'Original',
    '#',
    array('async' => true,
          'update' => 'content',
                  'id' => 'remanufactured-link'
        )
);
<div id="content">
</div>

Which implies a few things about the controller you are calling this view from (e.g. the index action will be invoked by clicking the link etc...).

like image 1
savedario Avatar answered Nov 14 '22 22:11

savedario