Using Ajax in Cakephp 2.0

Asked

Viewed 1,228 times

0

I cannot use the normal syntax of Ajax in the Cakephp. I’ve seen some things about Jshelper, but I can’t do what I want.

What can I call a action of controller for Ajax sending certain data and then receiving the result of action in view?

  • 1

    Put the code you tried, will make it easier to try to visualize the problem and help.

2 answers

1

I don’t know about Cake, I work with Codeigniter, but it can’t be much different. What I do is, in the ajax action I call the controller and the simplest is to give an echo (not the most recommended, just for testing) and the printed echo value I get in the Success Return. Something like that:

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";
    }
}

I hope it helps

1


There is not much secret, that is the path you are following using the Jshelper. First you need to include the helper in his Controller:

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

And to illustrate, you have a method so that will return one array containing some parameters:

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

To View corresponding to another Controller (teste_ajax, for example) let’s put only one 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 answer in the element #sponse, which is mine div last-line.

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

  • 1

    I recommend this way by using resources from the framework itself.

  • Thanks! It worked!

  • Nice to be able to help! Don’t forget to mark this answer as accepted, so you can help others with the same question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.