Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to retrieve data sent by Ajax in Cakephp?

I have been stuck at this problem for a whole day. What im trying to do is to send 2 values from view to controller using Ajax. This is my code in hot_products view:

<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 dont know how to get 2 values which are start_time and end_time. Please help me. Thanks in advance. PS: im using cakephp 2.3

like image 453
Tung Pham Avatar asked Dec 02 '13 11:12

Tung Pham


1 Answers

$this->request->data gives you the post data in 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've an error in your ajax,

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

    data: {"start_time": from, "end_time": to },
    success: function(data){
        alert("success");
    }
});
like image 192
Anil kumar Avatar answered Sep 29 '22 19:09

Anil kumar