Using Ajax in CakePHP 2.0

0

I can not use the normal Ajax syntax in CakePHP . I've seen a few things about JsHelper , but I can not do what I want.

How can I call a action of controller by Ajax sending certain data and then receive the result of action in view ?

    
asked by anonymous 27.02.2014 / 13:37

2 answers

1

There is not much secret, this is the path you're following using JsHelper . First you need to include the helper in your Controller :

public $helpers = array('Js' => array('Jquery'));

And for example, you have a method so it will return a array containing some parameters:

public function ajax() {
    $this->render(false, false);
    debug($this->request->params);
}

The View corresponding to another Controller ( teste_ajax , for example) we will only put a button, passing two parameters, foo and bar :

echo $this->Js->submit('Enviar', array('update' => '#response', 'url' => array('action' => 'ajax', 'foo', 'bar')));
echo $this->Html->script('jquery');
echo $this->Js->writeBuffer(array('inline' => 'true'));
echo "<div id='response'></div>";

Note that I set to display my response on the #response element, which is my div of the last line.

See is clear and you can understand to be able to implement according to your needs.

    
27.02.2014 / 15:21
1

I do not know about Cake, I work with Codeigniter, but it should not be very different. What I do is, in the action of ajax I call the controller and the simplest is to give an echo (it is not the most recommended, just for test) and the printed value of the echo I receive in the return of success. Something like this:

js:

$.ajax({
    url: 'ajax/action',
    type: 'GET',
    data: {chave:valor},
    success: function (retorn) {
        $('#content').html(retorn); //colocar o retorno no #content
    },
    error: function () {
        alert('Erro');
    }
}); 

php:

class Ajax extends CI_Controller {

    public function action()
    {
         echo "teste";
    }
}

Hope it helps

    
27.02.2014 / 14:47