How to get data sent by Ajax to Cakephp?

I am stuck with this problem all day. What I'm trying to do is send 2 values ​​from the view to the controller using Ajax. This is my code in the view hot_products:

<script>
$(function(){
    $('#btnSubmit').click(function() {
    var from = $('#from').val();
    var to = $('#to').val();
    alert(from+" "+to);
    $.ajax({
        url: "/orders/hot_products",
        type: 'POST',

        data: {"start_time": from, "end_time": to,
        success: function(data){
            alert("success");
            }
        }
    });
});
});

and my hot_products controller:

public function hot_products()
{   
    if( $this->request->is('ajax') ) {

        $this->autoRender = false;


                    //code to get data and process it here
      }
}

I don't know how to get 2 values ​​which are start_time and end_time. Please help me. Thank you in advance. PS: im using cakephp 2.3

+4
source share
2 answers

$this->request->data provides you with data to write to your controller.

public function hottest_products()
{   
    if( $this->request->is('ajax') ) {
        $this->autoRender = false;
    }

    if ($this->request->isPost()) {

        // get values here 
        echo $this->request->data['start_time'];
        echo $this->request->data['end_time']; 
    }

}

Update you have a bug in your ajax,

$.ajax({
    url: "/orders/hot_products",
    type: 'POST',

    data: {"start_time": from, "end_time": to },
    success: function(data){
        alert("success");
    }
});
+4
source

If you use the POST method :

 if($this->request->is('ajax'){
$this->request->data['start_time'];
$this->layout = 'ajax';
}

OR

public function somefunction(){  
$this->request->data['start_time'];  
$this->autoRender = false;

ANd, GET:

 if($this->request->is('ajax'){
$this->request->query('start_time');
$this->layout = 'ajax';
}  

public function somefunction(){  
$this->request->query('start_time');  
$this->autoRender = false;
+2

All Articles