Tung Pham
Tung Pham

Reputation: 599

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

Upvotes: 5

Views: 10242

Answers (2)

Anil kumar
Anil kumar

Reputation: 4177

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

Upvotes: 5

Aaliya
Aaliya

Reputation: 131

If you method is POST:

 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 if method is GET:

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

OR

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

Upvotes: 3

Related Questions