How to get back data from a function via ajax?

Asked

Viewed 849 times

0

I have an ajax in my view add that makes an asynchronous request in an action test in my controller, in this function I need to return the variable $balance to my view add, I would like to know how I 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 job, I would like to send this variable to my view and print it there. But I don’t know how to send it to my view.

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 view test.ctp.


On the Javascript side, you need to define a callback which determines what will be done when the request reply arrives. The part of Ajax 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);
    }
});
  • I don’t have a view test, I have a view add, and I have an ajax function that sends me to action test in my controller, I would like to know how to return this $balance variable to my view add.

  • 1

    The test action renders a view test (if any). And that’s what’s sent back to Javascript (which I assume is in the add view). Maybe the problem is in Javascript then. Because that’s where you have access to the result of the Ajax request.

  • 1

    @Devidyoliviera You can even use one action without a view, but for this you must inform on controller that it should not automatically render a view thus $this->autoRender = false;

  • @bfavaretto So in my action if I put the set it already sends straight to my ajax function. Basically I need to figure out how to get that data there. That’s it?

  • 1

    I think so. Don’t want to edit the question and include the JS part that makes the ajax request? @Devidyoliviera

  • @bfavaretto I edited the question.

  • 1

    @Devidyoliviera I edited the answer

  • @bfavaretto Thanks for your attention. Thank you very much.

Show 3 more comments

Browser other questions tagged

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