How do I get the return data of a function via ajax?

0

I have an ajax in my view add that does an asynchronous request in an action test in my controller, in this function I need to return the $ balance variable for my view add, I would like to know how I can send this data and how they arrive in my view.

Below is my ajax function:

    $('#entity').click(function(){
    var campanha = $('#entity').serialize()
    console.log(campanha); 
     $.ajax({
       type: 'post',               
       data: campanha,
       url:'<?php echo Router::url('/emailMarketings/test/'); ?>',
       })
    });

And here's my action:

    public function test() {

    if ($this->request->is('post')) {
        $teste = $this->request->data;
    }
    // debug($teste); die;

    // $this->redirect($this->referer());

   $balance = $this->Balance->find('first', array('order' => array('Balance.cota_email=' => $teste['Balance']['campaigns'])));
}

This is my role, I would like to send this variable to my view and print it there. But I do not know how to send her to my view.

    
asked by anonymous 06.04.2015 / 18:52

1 answer

2

At the end of this method test , before closing the function, add:

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

This will leave a variable $balance available in your test.ctp view.

On the JavaScript side, you need to define a callback that determines what will be done when the request response arrives. The Ajax part looks like this:

$.ajax({
    type: 'post',               
    data: campanha,
    url:'<?php echo Router::url('/emailMarketings/test/'); ?>',
    success: function(data) {
        console.log('Retornados os seguintes dados:');
        console.log(data);
    }
});
    
06.04.2015 / 18:54