how to retrieve data sent by Ajax in Cakephp?

房东的猫 提交于 2020-01-11 09:13:46

问题


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


回答1:


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



回答2:


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;


来源:https://stackoverflow.com/questions/20327049/how-to-retrieve-data-sent-by-ajax-in-cakephp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!