Question

I'm trying to send a simple ajax request in cakephp. I've to send ajax requests for many buttons. But I'm just trying a simple ajax request first. But it's not working for some reason. This is what I've done so far. This is my code.

show.ctp

<?php echo $this->Html->script('jquery', FALSE); ?>

<?php

echo $this->Form->create();
echo $this->Form->input('field', array('id'=>'field'));
echo $this->Js->submit('Send', array(
'before'=>$this->Js->get('#sending')->effect('fadeIn'),
'success'=>$this->Js->get('#sending')->effect('fadeOut'),
'update'=>'#success'
));

?>

<div id='sending' style="display:none"> Counz[dot]gif will be displayed </div>
<div id='success'></div>

controller

var $name = 'count';

    public $helpers = array('Js' => array('Jquery'));
    //var $helpers = array('Ajax', 'Javascript');
    var $components = array('RequestHandler');

public function show(){
        if($this->RequestHandler->isAjax()){
            $this->render('success', 'ajax'); //ajax tells the layout it should use

        }else{
            $this->set('for_map', $this->count->find('all'));

        }
    }

success.ctp

<p>It's working</p>

Also ajax.ctp is there by default.

Please tell me what am I doing wrong. Thanks. :)

No correct solution

OTHER TIPS

It's better not to post to self when doing ajax requests.

show.ctp

echo $this->Form->create('Count', array('action'=>'ajaxShow'));

controller

public function ajaxShow(){

    $this->layout = 'ajax';


    if($this->RequestHandler->isAjax()){
         $this->render('success', 'ajax'); //ajax tells the layout it should use
    }
}

I know this thread is very old but I'll just share my answer. You can just do normal ajax call, for example your url is 'users/items' type is GET then in your:

UsersController.php

public function items(){
 // some logic to get items
 $this->set('items',$items);
 $this->layout = null; //remove default layout.
 $this->render('ajax/items'); // here I use View/Users/ajax/items.ctp
}

items.ctp

//you can return json
<?php echo json_encode($items); ?>

//or

//your own format
<?php 
 foreach($items as $item){
      //some output
 }
?>

now that output in items.ctp will be in your js' success property. just make sure you parse the returned json.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top